【发布时间】:2015-08-21 08:45:33
【问题描述】:
我正在使用 Swift 调用 Openweather 地图 API,我需要从响应中返回一个特定值作为字符串。
但是,当我尝试返回值时,由于 JSON 无法转换为字符串,因此出现错误。
func callWeatherServ(name:String, completion:(Dictionary<String,AnyObject>) -> Void)
{
var baseUrl: String = "http://api.openweathermap.org/data/2.5/weather"
var url: String = "\(baseUrl)?q=\(name)"
let finalUrl: NSURL = NSURL(string: url)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(finalUrl, completionHandler: {data, response, error -> Void in
if error != nil
{
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
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)")
}
let json = JSON(jsonResult)
println("response is \(json) ")
var weathername = json["weather"][0]["main"]
if (weathername != nil)
{
return weathername
}
})
task.resume()
}
我明白了,因为我们使用了返回类型为 void 的闭包,所以我们应该使用完成处理程序。但我不知道我们如何做到这一点。
如果我们将完成处理程序作为参数传递,我们如何调用函数?
【问题讨论】:
-
做
completion(weathername)而不是return weathername然后使用我的示例链接中的完成调用您的函数。另外要小心,您似乎要解析 JSON 两次,一次使用 NSJSONSerialization,一次使用 SwiftyJSON... -
@Eric 很抱歉,我无法将我的示例与您的示例联系起来,因为我是学习 swift 的新手。您能否仅用我的示例指导我。
标签: swift swifty-json completionhandler