Search code examples
swiftparsingweather-api

JSON parsing error in Swift 2.0


I'm learning to code in Swift 2.0 and I got stuck while compiling it into simulator. The self.setLabels(data!) line displays an info Thread 1: EXC_BAD_INSTRUCTION. Can anyone help me with this? I'm doing a trial-and-error technique but no luck yet...

 lass ViewController: UIViewController {

@IBOutlet weak var cityNameTextField: UITextField!
@IBOutlet weak var cityNameLabel: UILabel!
@IBOutlet weak var cityTempLabel: UILabel!

@IBAction func getWeatherDataClick(sender: AnyObject)  {
    getWeatherData("http://api.openweathermap.org/data/2.5/weather?q=" + cityNameTextField.text! + "")
}

override func viewDidLoad() {
    super.viewDidLoad()
    getWeatherData("http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0")
    // 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 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) {
    let jsonResult = AnyObject? ()
    do {
        if let jsonResult = try NSJSONSerialization.JSONObjectWithData(weatherData, options: []) as? NSDictionary {
        print(jsonResult)
        }
    } catch {
            print(error)
        }
    if let name = jsonResult!["name"] as? String {
    cityNameLabel.text = name
    }
if let main = jsonResult!["main"] as? NSDictionary {
    if let temp = main["temp"] as? Double {
        cityTempLabel.text = String(format: "%.1f", temp)
        }
    }
};

}


Solution

  • First guess would be: data == nil. Your function: setLabels: is not prepared to receive nil argument. Try to change declaration of this function to:

    func setLabels(weatherData: NSData?)
    

    Or even better handle data == nil possibility before calling setLabels, in your NSURLSession block:

    if let weatherData = data as? NSData {
        //your data is not nil
        //you can securely call setLabels
        self.setLabels(weatherData)
    } else {
       //ooops sth goes wrong your data is nil, try to figure out why
    }