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 からのキャストですか? AnyObject は Dictionary 型ではないオブジェクトである可能性があるため、 to Dictionary は安全ではありません。そのため、キャスト演算子は、キャスト結果を暗黙as!as?にアンラップする必要があります。また、AnyObject? はオプションです。解決策は、最初に JSON デシリアライゼーションの結果をアンラップしてから、ディクショナリにキャストすることです。

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 に答える