NSURLConnection的sendAsynchronousRequest不能得到变量out关闭 [英] NSURLConnection sendAsynchronousRequest can't get variable out of closure

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

问题描述

我想从使用POST PHP页面简单的文本响应。我有以下的code:

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
}

虽然这code不抛出任何错误,当我拨打电话,以这样的:

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

println(post(url, info: data))

只打印:没事返回,即使如果我改变行:

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?

推荐答案

这是调用正在使用一个完成处理程序块/关闭异步函数。所以,你需要聘请完成处理模式在自己的code。这包括改变方法的返回类型的虚空并增加了新的 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的现在是正式去precated,它可能是更好地使用 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
}

和你怎么称呼它,像这样:

And you call it like so:

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)

请注意,保持这个简单,我采用的尾随闭包语法(见<α追踪闭幕的部分href=\"https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-XID_151\"相对=nofollow>雨燕编程语言:的闭包),但希望它描述了一个思路:不能立即返回异步方法的结果,因此提供了一个完成处理程序结束将被调用时,异步方法就完成了。

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不能得到变量out关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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