Search code examples
iosxcodeswiftpostnsurlconnection

Swift - Return data from NSURLSession when sending POST request


I can send a POST request in Swift using the below code

func post() -> String{
    let request = NSMutableURLRequest(URL: NSURL(string: "http://myserverip/myfile.php")!)
    request.HTTPMethod = "POST"
    let postString = "data=xxxxxxx"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in
        if error != nil {
            println("error=\(error)")
            return
        }

        println("response = \(response)")

        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("responseString = \(responseString!)")

    }
    task.resume()



    return "";//how would i return data here
}

I need to return the result, but this isn't possible since the network request is asynchronous. I think I can use a listener to wait for the result and then return it, but I'm not sure how this would work or how to implement it If anyone could help, I would greatly appreciate it I am new to both iOS and Swift


Solution

  • Your post function might be like:

    func post(completionHandler: (response: String) -> ()) { your code }
    

    And in the response part:

    let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
    completionHandler(response: responseString)
    

    Finally, you can call your post method like:

    post( {(response: String) -> () in
                   println("response = \(response)")})