我正在构建一个应用程序,尝试从 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/