cakes88
cakes88

Reputation: 1917

HTTPS Post in Swift 2 - Using NSURLSession/NSMutableURLRequest

Using swift 2, new to the language. My goal is to send a simple post request to an API, then parse the response. I haven't found a clear way to do this and any attempt I make fails. Here is what I have:

func restURL() {
        let xmlStr: String? = "<webservices><WebService type='test'><WSName>test</WSName><select>select * from receipts where id = '1234'</select></WebService></webservices>"
        let session = NSURLSession.sharedSession()
        let url = NSURL(string: "https://apiwebaddress.com/post" as String)!
        let request = NSMutableURLRequest(URL: url)
        let post:NSString = xmlStr!
        let postData:NSData = post.dataUsingEncoding(NSUTF8StringEncoding)!
        request.HTTPMethod = "POST"
        request.HTTPBody = postData
        request.setValue("0", forHTTPHeaderField: "Content-Length")
        request.setValue("application/xml", forHTTPHeaderField: "Content-Type")
        request.setValue("gzip,deflate", forHTTPHeaderField: "Accept-Encoding")
        request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")

I believe I set this up right, I want to send this then get the xml in the body of the response back but I'm not sure where to go from here. Everything I've read is deprecated or confusing. Can someone explain how to accomplish my goal in simple terms? Thanks in advance

Upvotes: 1

Views: 1871

Answers (2)

ProblemSlover
ProblemSlover

Reputation: 2537

Here is the snipped I made based on my research how requests can be performed with NSURLSession. I added a few comments to make the code more readable :)

 func restURL() {

        {
             let xmlStr: String? = "<webservices><WebService type='test'><WSName>test</WSName><select>select * from receipts where id = '1234'</select></WebService></webservices>"
            var request = NSMutableURLRequest(URL: NSURL(string: url))
            var session = NSURLSession.sharedSession()
            request.HTTPMethod = "POST"
            let post:NSString = xmlStr!
            let postData:NSData = post.dataUsingEncoding(NSUTF8StringEncoding)!
            request.HTTPBody = postData
            request.addValue("application/xml", forHTTPHeaderField: "Content-Type")
            request.addValue("gzip,deflate", forHTTPHeaderField: "Accept-Encoding")
            request.addValue("Keep-Alive", forHTTPHeaderField: "Connection")

            var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
                println("Response: \(response)")
                var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("Body: \(strData)")

                /*Parse data here */
              // Here an example how it can be done in case of json response:
                var err: NSError?
                var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary


            }) // var task

            task.resume()

        } // End restURL

Upvotes: 5

myles
myles

Reputation: 1671

Not a straight solution to your issue but there is a third party framework called Alamofire (link here) which makes doing things like this cleaner and easier in my opinion.

There are examples of how to perform requests like/similar to yours.

Upvotes: 1

Related Questions