2015-01-25 5 views
-2

Я получаю эту ошибку при запуске моего кода: fatal error: unexpectedly found nil while unwrapping an Optional value, что может быть причиной этого?Неустранимая ошибка: неожиданно найдено нуль при развертывании Необязательное значение

var bodyData = "tel_client=\(phoneNumber)&id_pays=\(phoneCode)&datetime_alibi=\(getDateTimeFormat(date))&tel_contact=\(to)&nb_rappel_alibi=1&pr_rappel_alibi=5" 
//println(bodyData) 
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding) 
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { 
    (response, data, error) in 
    var error: NSError? 
    var jsonData: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:nil, error: &error) as NSDictionary 

    if jsonData["success"] as Int == 1 { 
     let alertView = UIAlertView(title: "GOOD", message: nil, delegate: self, cancelButtonTitle: "ok") 
     alertView.show() 
    } else { 
     let alertView = UIAlertView(title: "ERROR", message: jsonData["message"] as? String, delegate: self, cancelButtonTitle: "ok") 
     alertView.show() 
    } 
} 
+0

Вы должны проверить, была ли ошибка, поскольку jsonData может быть нулевой, если есть ошибка. –

ответ

1

JSONObjectWithData возвращает необязательный. Отсюда и возникает ваша ошибка. Развертывание будет устранено.

var jsonData = NSJSONSerialization.JSONObjectWithData(data, options:nil, error: &error) as? NSDictionary 

// unwrap the optional 
if let json = jsonData { 
    if json["success"] as Int == 1 { 
     let alertView = UIAlertView(title: "GOOD", message: nil, delegate: self, cancelButtonTitle: "ok") 
     alertView.show() 
    } else { 
     let alertView = UIAlertView(title: "ERROR", message: json["message"] as? String, delegate: self, cancelButtonTitle: "ok") 
     alertView.show() 
    } 
} else { 
    // jsonData was nil 
} 
+0

Большое вам спасибо! –