0

我正在构建一个试图从 OpenWeatherMap API 提取数据的应用程序,但在这一行:

let json = NSJSONSerialization.JSONObjectWithData(weatherData, options:NSJSONReadingOptions.AllowFragments, error:nil) as NSDictionary

我收到此错误:'AnyObject?不能转换为 NSDictionary';你的意思是用作!?

这是我的代码:

import UIKit

class ViewController: UIViewController {


@IBAction func ConfirmLocation(sender: AnyObject) {
}

@IBOutlet weak var LocationSearchLabel: UITextField!

@IBOutlet weak var LocationLabel: UILabel!

@IBOutlet weak var LocationTemperature: UILabel!


override func viewDidLoad() {
    super.viewDidLoad()
    getOpenWeatherFeed("api.openweathermap.org/data/2.5/weather?q=London,uk")
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}



func getOpenWeatherFeed(urlString: String)
{
    let urlAddress = NSURL(string: urlString)
    let task = NSURLSession.sharedSession().dataTaskWithURL(urlAddress!) {(data, response, error) in
    dispatch_async(dispatch_get_main_queue(), { self.pushDataToLabel(data)})
    }

    task.resume()
}

func pushDataToLabel(weatherData: NSData){
    var jsonError: NSError?

    let json = NSJSONSerialization.JSONObjectWithData(weatherData, options:NSJSONReadingOptions.AllowFragments, error:nil) as NSDictionary

    if let name = json["name"] as? String{

        LocationLabel.text = name}

    if let main = json["main"] as? NSDictionary{
        if let temp = main["temp"] as? Double{
            LocationTemperature.text = String(format: "%.1f", temp)
        }
    }
}


}
4

1 回答 1

0

问题是来自 AnyObject 的演员表?to Dictionary 是不安全的,因为 AnyObject 可能是一个不属于 Dictionary 类型的对象,因此强制转换运算符必须是as!或者as?您是否想要隐式解包强制转换结果。还有任何对象?是可选的。解决方案是首先解开 JSON 反序列化的结果,然后转换为 Dictionary:

if let json = NSJSONSerialization.JSONObjectWithData(weatherData, options:NSJSONReadingOptions.AllowFragments, error:nil) {
    if let dictionary = json as? Dictionary {
        //work with dictionary here
    } else {
        //The provided data is in JSON format but the root json object is not a Dictionary
    }
} else {
    //The provided data is not in JSON format
}

在第一行中,JSON 数据被反序列化,这可能会产生任何对象,也可能会失败。如果失败,则返回 nil 并调用外部 else 情况。如果序列化成功,则 json 对象将转换为 Dictionary,然后您可以使用它。一个简短但不安全的解决方案是

let json = NSJSONSerialization.JSONObjectWithData(weatherData, options:NSJSONReadingOptions.AllowFragments, error:nil)! as! NSDictionary
于 2015-10-30T00:53:55.740 回答