Fred37b Fred37b - 5 months ago 10
Swift Question

How display in the UI a JSON in swift

I try to adapt my android application on Iphone, but when I ask my server to get a JSON i have a fatal error :
fatal error: unexpectedly found nil while unwrapping an Optional value

I think I have bad initialize my text field in my story board or something else but I can't find my error.

The "print(jsonResult)" give me the good JSON but after I have my fat error that appear.

import UIKit

class ViewController: UIViewController {



@IBOutlet weak var labelCategory: UILabel!
@IBOutlet weak var imageViewOneTrash: UIImageView!
@IBOutlet weak var textFieldCoordinate: UITextField!
@IBOutlet weak var textFieldAddress: UITextField!
@IBOutlet weak var buttonShare: UIButton!
@IBOutlet weak var buttonCoppy: UIButton!
@IBOutlet weak var buttonDelete: UIButton!
@IBOutlet weak var buttonMaps: UIButton!
@IBOutlet weak var addressTxtFld: UITextField!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

// 1
let urlAsString = "http://www.website.sample"
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()

//2
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
print(error!.localizedDescription)
}

// 3
do{
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? [String:AnyObject] {

print(jsonResult)
// 4
let jsonAddress: String! = jsonResult["trash_temp_address"] as! String

dispatch_async(dispatch_get_main_queue(), {
self.addressTxtFld.text = jsonAddress
})
}

}catch let error as NSError {
print(error.localizedDescription)
}

})
// 5
jsonQuery.resume()

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}


The result of the print(jsonResult) is :

["result": <__NSArrayM 0x15d62770>(
{
"cat_name" = Mobilier;
"country_name" = France;
"town_name" = Toulon;
"town_postal_code" = 83200;
"trash_temp_address" = "278-338 Chemin du Jonquet";
"trash_temp_date_time" = "2016-05-22 17:49:14";
"trash_temp_fk_category" = 2;
"trash_temp_id" = 99;
"trash_temp_img" = "/pics/IMG_20160622_174846.jpg.png";
"trash_temp_latitude" = "43.1395197";
"trash_temp_longitude" = "5.9106404";
}
)
]

Answer
  • The root object is a dictionary with one key result.
  • The value for key result is an array of dictionaries

This gets the value for key trash_temp_address

if let jsonRootObject = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject] { // mutable containers are not needed

    print(jsonRootObject)
    if let jsonResult = jsonRootObject["result"] as? [[String:String]],
       jsonAddress = jsonResult[0]["trash_temp_address"] {    
          dispatch_async(dispatch_get_main_queue()) {
             self.addressTxtFld.text = jsonAddress
          }
    }
    ...