NSURLConnection sendAsynchronousRequest 无法从关闭中获取变量 [英] NSURLConnection sendAsynchronousRequest can't get variable out of closure

查看:22
本文介绍了NSURLConnection sendAsynchronousRequest 无法从关闭中获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 POST 从 PHP 页面获取简单的文本响应.我有以下代码:

I'm trying to get a simple text response from a PHP page using POST. I have the following code:

func post(url: String, info: String) -> String {
    var URL: NSURL = NSURL(string: url)!
    var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
    var output = "Nothing Returned";
    request.HTTPMethod = "POST";
    var bodyData = info;
    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()){

        response, data, error in

        output = (NSString(data: data, encoding: NSUTF8StringEncoding))!


    }

    return output
}

虽然这段代码没有抛出任何错误,但当我像这样调用它时:

While this code does not throw any errors, when I make a call to it like this:

println(post(url, info: data))

它只打印:Nothing Returned",即使我要更改行:

It only prints: "Nothing Returned" even though if I were to change the line:

output = (NSString(data: data, encoding: NSUTF8StringEncoding))!

为此:

println((NSString(data: data, encoding: NSUTF8StringEncoding)))

它确实打印出正确的响应.我这里的变量有问题吗?

it does print out the proper response. Am I doing something wrong with my variables here?

推荐答案

这是调用使用完成处理程序块/闭包的异步函数.因此,您需要在自己的代码中使用完成处理程序模式.这包括将方法返回类型更改为 Void 并添加一个新的 completionHandler 闭包,该闭包将在异步调用完成时调用:

This is calling asynchronous function that is using a completion handler block/closure. So, you need to employ the completion handler pattern in your own code. This consists of changing the method return type to Void and adding a new completionHandler closure that will be called when the asynchronous call is done:

func post(url: String, info: String, completionHandler: (NSString?, NSError?) -> ()) {
    let URL = NSURL(string: url)!
    let request = NSMutableURLRequest(URL:URL)
    request.HTTPMethod = "POST"
    let bodyData = info
    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { response, data, error in
        guard data != nil else {
            completionHandler(nil, error)
            return
        }

        completionHandler(NSString(data: data!, encoding: NSUTF8StringEncoding), nil)
    }
}

或者,由于 NSURLConnection 现在已被正式弃用,最好使用 NSURLSession:

Or, since NSURLConnection is now formally deprecated, it might be better to use NSURLSession:

func post(url: String, info: String, completionHandler: (NSString?, NSError?) -> ()) -> NSURLSessionTask {
    let URL = NSURL(string: url)!
    let request = NSMutableURLRequest(URL:URL)
    request.HTTPMethod = "POST"
    let bodyData = info
    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        dispatch_async(dispatch_get_main_queue()) {
            guard data != nil else {
                completionHandler(nil, error)
                return
            }

            completionHandler(NSString(data: data!, encoding: NSUTF8StringEncoding), nil)
        }
    }
    task.resume()

    return task
}

你这样称呼它:

post(url, info: info) { responseString, error in
    guard responseString != nil else {
        print(error)
        return
    }

    // use responseString here
}

// but don't try to use response string here ... the above closure will be called
// asynchronously (i.e. later)

注意,为了保持简单,我采用了尾随闭包语法(请参阅 The Swift Programming Language: Closures),但希望它能说明这个想法: 不能立即返回异步方法的结果,因此提供一个完成处理程序闭包,在异步方法完成时将调用该闭包.

Note, to keep this simple, I've employed the trailing closure syntax (see Trailing Closure section of The Swift Programming Language: Closures), but hopefully it illustrates the idea: You cannot immediately return the result of an asynchronous method, so provide a completion handler closure that will be called when the asynchronous method is done.

这篇关于NSURLConnection sendAsynchronousRequest 无法从关闭中获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆