JSON SWIFT OpenWeatherMapAPI

标签 json swift weather-api openweathermap

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

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

我收到此错误:“AnyObject?不可转换为 NSDictionary';你的意思是使用 as! ?

这是我的代码:

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)
        }
    }
}


}

最佳答案

问题是来自 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 对象将被转换为字典,然后您可以使用它。一个简短但不安全的解决方案是

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

关于JSON SWIFT OpenWeatherMapAPI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33426613/

相关文章:

javascript - 在angularjs中使用JSONObject读取json

ajax - 如何在服务器上启用跨域请求?

ios - 如何使 dataTaskWithRequest 在 swift(Xcode 9,swift 4)中按时间顺序排列?

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

google-maps - 如何隐藏或显示 Google map 图层?

javascript - simpleweatherjs插件: Firefox asks me to share my location but wont display current temperature

PHP JSON GET 在网页上正确显示,但在 php 中不正确

c# - .NET Core - 读取 JSON 文件的转换日期

ios - DateFormatter 不返回 "HH:mm:ss"的日期

android - 吴 : How to take items from a JSONArray that has no name