Swift-发送POST请求时从NSURLSession返回数据

问题描述:

我可以使用以下代码在Swift中发送POST请求

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
}

我需要返回结果,但这是不可能的,因为网络请求是异步的.我想我可以使用侦听器等待结果然后返回,但是我不确定这将如何工作或如何实现 如果有人可以提供帮助,我将不胜感激 我对iOS和Swift都是新手

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

您的帖子功能可能类似于:

Your post function might be like:

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

在响应部分:

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

最后,您可以像这样调用post方法:

Finally, you can call your post method like:

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