JSON数据不会在swift中作为字符串返回

时间:2015-02-21 07:03:28

标签: ios json xcode string swift

我正在尝试从JSON对象返回数据作为字符串,但每当我尝试它返回nil如果有人可以帮助请找到下面的代码。我需要将currentWeather作为String返回其当前值我无法仅将数据作为字符串作为可选项返回。

    let urlPath = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=metric"
    let url: NSURL = NSURL(string: urlPath)!
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
        println("Task completed")
        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


          let jsonDictionary = jsonResult as NSDictionary
            let mainDictionary = jsonResult.valueForKey("main") as NSDictionary
            let currentWeather = mainDictionary.valueForKey("humidity") as? NSString
        println(currentWeather)



    })
    task.resume()

1 个答案:

答案 0 :(得分:0)

我试过了代码。 '湿度'是一个Int,而不是String。所以你应该使用

let currentWeather = mainDictionary.valueForKey("humidity") as Int