1

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

cakes88
  • 1,857
  • 5
  • 24
  • 33
  • 1
    Everything seems to be right, but NSURLConnection is missing. Look at the snipped here http://stackoverflow.com/questions/24176362/nsurlconnection-using-ios-swift – ProblemSlover Oct 13 '15 at 15:34
  • #4 in PREMKUMAR's answer there gives me: '(NSURLResponse!, NSData!, NSError!) -> Void' is not convertible to '(NSURLResponse?, NSData?, NSError?) -> Void' @ProblemSlover – cakes88 Oct 13 '15 at 16:05
  • And it's also deprecated – cakes88 Oct 13 '15 at 16:07
  • Added a snipped how it can be achieved with NSURLSession./ Please let me know if it works for you – ProblemSlover Oct 13 '15 at 17:08
  • 1
    Don't you feel like my answer is worth to be accepted? I've just noticed you used the code I posted in one of your questions, , so I believe I didn't waste my time helping you and there should have been some pay off from your side. – ProblemSlover Oct 16 '15 at 04:57
  • lol.. keepin people on top of their games.. nice – cakes88 Oct 16 '15 at 14:54

2 Answers2

5

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
ProblemSlover
  • 2,538
  • 2
  • 23
  • 33
1

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.

myles
  • 1,681
  • 1
  • 15
  • 27