如何在swift中返回NSDictionary,同时等待其值设置?

时间:2015-03-16 14:08:23

标签: swift nsdictionary

请饶我。我是swift的新手

我的问题是我无法返回我的NSDictionary这是我的功能

   private func request(url:String, baseURL:String) -> NSDictionary {
       var dict:NSDictionary!
        var request = HTTPTask()
        request.requestSerializer = HTTPRequestSerializer()
        request.requestSerializer.headers[headerKey] = getToken() //example of adding a header value

        request.baseURL = baseURL

        request.GET(url, parameters: nil, success: {(response: HTTPResponse) in
            if var data = response.responseObject as? NSData {
                let str = NSString(data: data, encoding: NSUTF8StringEncoding)
                var error: NSError?
                dict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
              println("response: \(dict)") 
            }
            },failure: {(error: NSError, response: HTTPResponse?) in
                println("error: \(error)")
        })

       return dict 
    }

返回dict就像{}一样空,但当函数内的println("response: \(dict)")似乎记录我的数据时。

我认为我的函数返回一个空对象,因为.GET方法在不同的线程中运行并等待响应。

任何人都可以帮助我,任何评论都可以。

1 个答案:

答案 0 :(得分:1)

你是对的,请求在另一个线程中异步运行,我建议使用完成处理程序。

private func request(url: String, baseURL: String, completion: (result: NSDictionary) -> Void) {

    var dict:NSDictionary!
    var request = HTTPTask()
    request.requestSerializer = HTTPRequestSerializer()
    request.requestSerializer.headers[headerKey] = getToken() //example of adding a header value

    request.baseURL = baseURL

    request.GET(url, parameters: nil, success: {(response: HTTPResponse) in
        if var data = response.responseObject as? NSData {
            let str = NSString(data: data, encoding: NSUTF8StringEncoding)
            var error: NSError?
            dict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
          println("response: \(dict)")
          completion(result: dict) 
        }
        },failure: {(error: NSError, response: HTTPResponse?) in
            println("error: \(error)")
            completion(result: nil) //this is not the best option, better would be to return error in error handler
    })
}

有关详细信息,请查看以下内容:http://www.veasoftware.com/tutorials/2015/1/13/completion-handlers-swift-programming-tutorial