2016-12-12 29 views
-5

這個問題已被問及一百萬次,但它仍然讓我困惑。 我有應用程序連接到服務器以登錄,一切都很好,直到用戶輸入不正確,服務器返回零。如何防止我的應用程序崩潰致命錯誤:意外地發現零,同時展開一個可選值(Swift 3)

// A method for the login button 
     @IBAction func loginButton(_ sender: UIButton) { 
    parameters["email"] = email?.text 
    parameters["password"] = password?.text 
    Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: token).responseJSON { 
     (response) in 
     print(response.result.value!) 

     // Check if the servers return token and go to the next page 
     if response.result.value != nil { 
     self.performSegue(withIdentifier: "loginSegue", sender: nil) 
     } 
     if let tokenString = response.result.value as? String { 
      self.token["X-Auth-Token"] = tokenString 
     } 
    } 
} 

回答

1

在你print(response.result.value!)線,您使用的是!強制拆禮物response.result.value變量。這個變量是可選的,這意味着它不能保證有一個值。如果你在一個可選變量上使用!,那麼你基本上是在告訴編譯器:「別擔心,我保證它有一個值」。如果它確實沒有價值,它會崩潰。

解決方案: 變化,在響應第一行print(response.result.value)

相關問題