![](/img/trans.png)
[英]unexpectedly found nil while unwrapping an Optional value - Using ALAMOFIRE
[英]Alamofire using optional value with dictionary parameter
根據Apple對字典值的定義,由於鍵可能存在或不存在,因此從字典返回的任何值都是可選的
您還可以使用下標語法從字典中檢索特定鍵的值。 因為可以請求不存在任何值的鍵,所以字典的下標返回字典值類型的可選值。 如果字典中包含所請求鍵的值,則下標將返回一個可選值,其中包含該鍵的現有值。
我正在嘗試在參數字典中使用auth_token進行網絡調用。
let params = ["auth_token" : authToken()]
print(params["auth_token"]) // shows Optional(dwadhuiwahd)
字典中的值不是可選的。 我使用authToken()函數中的條件綁定並通過打印將其檢查出來。 但是,當打印出保存auth_token的字典鍵時,它會顯示為:
Optional(dawudhawhd)
這導致我的網絡請求失敗。
Alamofire.request(.GET, urlString, parameters: params, encoding: .JSON).responseJSON {
(response) in
//this fails
}
除非我對網址進行硬編碼。
let urlString = "https://staging.travelwithterra.com/api/v1/users/" + agentID + "/agent_info?auth_token=" + authToken()
Alamofire.request(.GET, urlString, encoding: .JSON).responseJSON {
(response) in //this doesnt fail }
我的問題是,Alamofire為何不考慮這一點? 或我在做什么錯,它殺了我!
********解**********
不要使用.JSON編碼! .URL編碼!!!
您只需要添加一個感嘆號。 如下所示。
print(params["auth_token"]!) // doesn't show Optional(dwadhuiwahd) :P
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.