Alamofire,致命错误:在打开Optional值时意外发现nil

时间:2016-05-02 13:04:48

标签: swift null alamofire

我正在处理我的应用程序,它在模拟器上运行正常。虽然我们在我的iphone上尝试过这种方法,但它却因不懈的错误而崩溃。任何想法?谢谢 error screenshot

 class connection{
var url: String = ""
func connectServer(url:String,completionHandler: (jsonResponse: JSON) -> ()) {    
    Alamofire.request(.GET, url)
        .responseJSON { (response) in
            let json = JSON(response.result.value!)
            //        print(json) // works fine
            completionHandler(jsonResponse: json)
    }
}

}

 func loadData(){
    let cn = connection()
    let url = "http://localhost:3000/api/v1/patients/user_id/"+userID
    // Call function to connect server by API with specific url
    cn.connectServer(url) { (jsonResponse) in
        //Parsing JSON file
        for item in jsonResponse["patients"].arrayValue{
            //pasring json
            }
            }}

1 个答案:

答案 0 :(得分:0)

试试这个:

var url: String = ""
    func connectServer(url:String,completionHandler: (jsonResponse: JSON) -> ()) {
        Alamofire.request(.GET, url)
            .responseJSON { (response) -> Void in
                guard response.result.isSuccess else {
                    print("Error while fetching remote rooms: \(response.result.error)")
                    completion(nil)
                    return
                }

                guard let value = response.result.value as? [String: AnyObject],
                    completionHandler(jsonResponse: value) else {
                        print("Malformed data received from fetchAllRooms service")
                        completion(nil)
                        return
                }


        }
    }