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