Alamofire使用带字典参数的可选值

时间:2016-08-10 17:44:12

标签: ios swift alamofire

通过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编码!!!

1 个答案:

答案 0 :(得分:0)

您只需要添加一个感叹号。如下所示。

print(params["auth_token"]!) // doesn't show Optional(dwadhuiwahd) :P