3

I found this awesome answer to posting data to php

The only problem is, I don't know how to return the data upon completion.

How can I make a completion handler for the following function?

func postToServer(postURL: String, postString: String) {
    let request = NSMutableURLRequest(URL: NSURL(string: postURL)!)
    request.HTTPMethod = "POST"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data, response, error in

        let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
        if responseString != nil {
            print("responseString = \(responseString!)")
        }

    }
    task.resume()
}

Edit: Maybe I didn't apply it correctly, but the suggested duplicate link did not solve my problem. Could somebody please provide an example of this? I've been stuck on this for like 3 weeks now. I just don't know how to pull the data from task when it's completed. I've been reading up a lot on closures, but I just don't see where or even how these are related. When I try to find functions related to task, it only gives response...and that returns nil if I don't type in sleep(3) after resume.

I've watched a bunch of videos where people have the same code as me and don't use a completion handler and still get data back... what gives?

Community
  • 1
  • 1
Trevor Wood
  • 2,347
  • 5
  • 31
  • 56
  • Possible duplicate of [How could I create a function with a completion handler in Swift?](http://stackoverflow.com/questions/30401439/how-could-i-create-a-function-with-a-completion-handler-in-swift) – Swifty Oct 02 '16 at 20:25
  • 1
    You're calling an asynchronous method, so if you want to return data, your function must also include a completion handler as an argument. If you want to use NSURL synchronously, there is an extension that does exactly that. http://stackoverflow.com/questions/26784315/can-i-somehow-do-a-synchronous-http-request-via-nsurlsession-in-swift – Sealos Oct 02 '16 at 21:41
  • Can you please explain what it is you're actually trying to accomplish? what do you want to do with the `responseString`? – Swifty Oct 04 '16 at 00:55

1 Answers1

2

This works in swift 3

func postToServer(_ completion:@escaping (( _ response: String, _ success: Bool )-> Void), postURL: String, postString: String) {
    let request = NSMutableURLRequest(url: NSURL(string: postURL)! as URL)
    request.httpMethod = "POST"
    request.httpBody = postString.data(using: String.Encoding.utf8)

    let task = URLSession.shared.dataTask(with: request as URLRequest){
        data, response, error in

        let responseString = String(data: data!, encoding: String.Encoding.utf8)
        if responseString != nil {
            print("responseString = \(responseString!)")
            completion(responseString!, true)

        }

    }
    task.resume()
  }
}
Mat
  • 6,236
  • 9
  • 42
  • 55