【问题标题】:JSON SWIFT OpenWeatherMapAPIJSON SWIFT OpenWeatherMapAPI
【发布时间】:2016-01-30 07:48:54
【问题描述】:

我正在构建一个尝试从 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)
        }
    }
}


}

【问题讨论】:

    标签: json swift weather-api openweathermap


    【解决方案1】:

    问题是来自 AnyObject 的演员表?到 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      • 2015-10-06
      • 2018-06-27
      • 1970-01-01
      相关资源
      最近更新 更多