我的swift应用程序无法返回字典值

时间:2016-05-22 01:39:43

标签: swift nsurlsession

该方法无法返回从GET请求中获取的值,其中变量res可以在任务部分中打印,但最终无法返回。

func lookUpTheWord(word:String) -> NSDictionary {
    var res = NSDictionary()
    let urlString = "https://wordsapiv1.p.mashape.com/words/" + word
    if let url = NSURL(string:urlString) {
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "GET"
        request.addValue("this is a key", forHTTPHeaderField: "X-Mashape-Key")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in
            if error != nil {
                print("\(error)")
                return
            }
            res = self.toJson(data!)
            print(res) //it works here
        }
        task.resume()
    }
    return res //res becomes nil
}

1 个答案:

答案 0 :(得分:1)

这是因为你在分配之前返回变量res。你会注意到res之后的func lookUpTheWord(word:String, completion: (NSDictionary->Void)) { var res = NSDictionary() let urlString = "https://wordsapiv1.p.mashape.com/words/" + word if let url = NSURL(string:urlString) { let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "GET" request.addValue("this is a key", forHTTPHeaderField: "X-Mashape-Key") request.addValue("application/json", forHTTPHeaderField: "Accept") let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if error != nil { res = self.toJson(data!) completion(res) } } task.resume() } } 是在它之后打印的。{1}}。这是因为HTTP请求不会立即发生 - 代码在完成之后执行,因此称为“异步”。

如果要使用HTTP请求中获取的变量,请在函数中使用闭包作为参数,并在请求完成时调用它。例如:

lookUpTheWord("word") { res in
    print(res)
}

像这样使用:

x = 1 2 3
    4 5 6

y = 7 8 9
    10 11 12