swift2 无法调用“jsonObjectWithData”

au9on6nz  于 2022-11-06  发布在  Swift
关注(0)|答案(6)|浏览(172)

我想不出如何解决这个问题。
这是来自youtube的一个教程,用来构建一个简单的天气应用程序。这个教程是在2015年3月上传的,因此用以前版本的Swift编写的,在那里它可以工作,而用现在的Swift 2就不行了。
我得到的错误是:““无法使用类型为”“的参数列表调用”“jsonObjectWithData”“(NSData,选项:无,错误:错误)'“

func getWeatherData(urlString:String) {

    let url = NSURL(string: urlString)

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!){ (data, response, error) in
        dispatch_async(dispatch_get_main_queue(), {

        self.setLabels(data)

        })

    }

    task.resume()

}

func setLabels(weatherData: NSData) {

    var jsonError: NSError

    let json = NSJSONSerialization.JSONObjectWithData(weatherData, options: nil, error: jsonError)

    if let name = json["name"] as? String {

        self.ResultLabel.text = name
    }
}
ocebsuys

ocebsuys1#

如果您想为Swift 2准备好这些代码,您必须运行JSONParser,并尝试捕获可能的错误。

private func httpGetRequest(request: NSURLRequest!, callback: (NSData?, String?) -> Void) {
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(request){
        (data, response, error) -> Void in
        if error != nil {
            callback(nil, error!.localizedDescription)
        } else {
            callback(data, nil)
        }
    }
    task!.resume()
}

func setLabels(weatherData: NSData) {
    do {
        let json = try NSJSONSerialization.JSONObjectWithData(weatherData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
        if let name = json["name"] as? String {
            self.resultLabel.text = name
        }
    } catch {
        print(error)
        self.resultLabel.text = "Lorem Ipsum"
    }
}

func loadWeatherData() {
    let weatherRequest = NSMutableURLRequest(URL: NSURL(string: "Your URL String goes here")!)
    httpGetRequest(weatherRequest){
        (data, error) -> Void in
        if error != nil {
            print("Error: \(error)")
        } else {
            self.setLabels(data!)
        }
    }
}

希望这将有助于解决您的问题。

yc0p9oo0

yc0p9oo02#

试试看:

var jsonError: NSError?
let json = NSJSONSerialization.JSONObjectWithData(weatherData, options: nil, error: &jsonError)
5m1hhzi4

5m1hhzi43#

在Swift 3.0和Swift 4.2中,请尝试以下操作...

do   {

let jsonData = try JSONSerialization.data(withJSONObject: your array or dictionary, options: JSONSerialization.WritingOptions()) as Data

let json = try JSONSerialization.jsonObject(with: jsonData as Data, options: JSONSerialization.ReadingOptions(rawValue: UInt(0)))

 }

 catch
{
}
7hiiyaii

7hiiyaii4#

您需要使用&将错误指针传递到NSJSONSerialization.JSONObjectWithData(...)

let json = NSJSONSerialization.JSONObjectWithData(weatherData, options: nil, error: &jsonError) // &jsonError points to the NSErrorPointer of the NSError object
sqougxex

sqougxex5#

在swift 3中,您可以尝试以下操作:

func setLabels(weatherData: NSData) {
        do {
            var jsonError: NSError
            let json = try JSONSerialization.jsonObject(with: weatherData as Data, options: []) as! NSDictionary

            if let name = json["name"] as? String {
                self.ResultLabel.text = name
            }
        } catch {

        }

    }
hpxqektj

hpxqektj6#

在Swift 3中,您可以使用下面的代码修复相同的错误:

do{
   let jsonData = try JSONSerialization.jsonObject(with: (data)!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: AnyObject]
}catch{
   print("Error while parsing JSON: Handle it")
}

相关问题