2 Replies
      Latest reply: Jan 26, 2017 4:05 AM by eskimo RSS
      JMPH Level 1 Level 1 (0 points)

        How would you write the code to post data in json format from swift to a web api?

        Lets say that you want to post new data to an api and it accepts the parameters firstname and familyname and lets say the url to the api is https://namesapi.example.com/api/names/ ?

        • Re: Post data to a web api in json format from swift
          JayCo Level 1 Level 1 (5 points)

          Easiest way is to use a combination of Alamofire and SwiftyJSON if your nested post request contains different types. If not then you can use Apple way which serializes your data into JSON format. It's just a case of posting this data and dealing with the result.

           

          if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) { 
           
          }
          
          • Re: Post data to a web api in json format from swift
            eskimo Apple Staff Apple Staff (7,005 points)

            Well, I would never create an API that encodes the concept of “first and family names”; that’s problematic on so many levels.  But hopefully that was just an example (-:

            btw If you’re curious about the details here, I strongly recommend you read Falsehoods Programmers Believe About Names.  It’s an absolute classic!  And if you’re looking for similar articles about other topics, type “falsehoods programmers believe about” into the Google search box and follow the auto completes (-:

            Anyway, back to your question…

            IMO the answer depends on how complex your web service API is, or will get.  If the web service API is as simple as you’ve said, I strongly recommend against bringing in complex frameworks to do this work.  Rather:

            1. Use JSONSerialization to create JSON data from a dictionary

            2. Post that data using URLSession

            However, if you’re talking to a complex web service API, with lots of requests taking lots of parameters, it may be worthwhile bringing in some frameworks to help.

            Share and Enjoy

            Quinn “The Eskimo!”
            Apple Developer Relations, Developer Technical Support, Core OS/Hardware
            let myEmail = "eskimo" + "1" + "@apple.com"