Fred37b Fred37b - 1 year ago 73
Swift Question

How display a JSON in the UI in swift

I try to adapt my Android application on iPhone, but when I ask my server to get a JSON object I have a fatal error:

fatal error: unexpectedly found nil while unwrapping an Optional value

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

gives me the good JSON but after I have my fatal 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() {
// Do any additional setup after loading the view, typically from a nib.

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

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

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

// 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 {

// 5


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

The result of the

["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 Source
  • 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

    if let jsonResult = jsonRootObject["result"] as? [[String:String]],
       jsonAddress = jsonResult[0]["trash_temp_address"] {    
          dispatch_async(dispatch_get_main_queue()) {
             self.addressTxtFld.text = jsonAddress
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download