Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Completion handler for Post to server

Tags:

swift

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?

like image 741
Trevor Wood Avatar asked May 14 '26 03:05

Trevor Wood


1 Answers

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()
  }
}
like image 194
Mat Avatar answered May 16 '26 23:05

Mat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!