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.
The print(jsonResult)
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() {
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";
}
)
]
Aucun commentaire:
Enregistrer un commentaire