NSURLSessionDataTask不会从请求中返回数据

时间:2014-09-17 19:43:05

标签: ios xcode swift nsurlconnection

我正在尝试向服务器发出请求,该服务器应返回我可以在其余应用程序中使用的数据。这是我的代码:

func makeNewUser() -> NSDictionary {
    var full_url = getFullUrl("makeNewUser")
    var toReturn: NSDictionary = NSDictionary()
    var request: NSURLRequest = NSURLRequest(URL:full_url)
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession.sharedSession()
    let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        println(response)
        var err: NSError?

        var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
        if(err != nil) {
            // If there is an error parsing JSON, print it to the console
            println("JSON Error \(err!.localizedDescription)")
        }
        toReturn = jsonResult
    });
    task.resume()
    self.delegate?.didReceiveAPIResults(toReturn)
    println(toReturn)
    return toReturn
}

我将调用数据发送给调用者中的委托函数,但它不可用。我认为这是因为请求是异步的。我处理这个问题的正确方法是什么,以便调用者知道在继续之前等待这些数据?

1 个答案:

答案 0 :(得分:1)

将委托调用移动到会话完成块:

func makeNewUser() {
    var full_url = getFullUrl("makeNewUser")
    var toReturn: NSDictionary = NSDictionary()
    var request: NSURLRequest = NSURLRequest(URL:full_url)
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession.sharedSession()
    let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        println(response)
        var err: NSError?

        var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
        if(err != nil) {
            // If there is an error parsing JSON, print it to the console
            println("JSON Error \(err!.localizedDescription)")
        }
        self.delegate?.didReceiveAPIResults(jsonResult)   // <<-----
    });
    task.resume()
}

你只需要知道结果不是立即可用的。您不希望阻止长时间运行的操作(如网络请求)上的功能(和UI)。