是否可以从POST调用

时间:2016-06-05 17:47:43

标签: swift

我有这段代码:

private func data_request(url : String)
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

    let url:NSURL = NSURL(string: self.self.newUrl.createUrl(url))!
    let session = NSURLSession.sharedSession()

    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

    let paramString = "data=Hello"
    request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

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

        guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
            print("error")
            return
        }

        let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)

    }

       task.resume()
    }
}

我称之为: var result = data_request("localhost/test");

这样可以正常工作,但是可以从请求函数返回结果吗?我的计划是将结果放在结果变量中。

1 个答案:

答案 0 :(得分:4)

您应该使用闭包来获取数据,因为NSURLSession API是异步的,这意味着您不知道数据何时到达。它可能是瞬间或在10秒内,你永远不会知道。您将立即从函数返回,但您将从闭包中获取值。

private func data_request(url : String, completion: (String) -> ()) {
    //...
    //...
    let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
    // Now call completion to pass the value
    completion(dataString)
}

当您需要调用该函数时,您将使用:

data_request("http://someapi.com/api") {
    dataString in
    print(dataString) // This is the string you passed to the completion
}