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

标签 ios swift alamofire

根据 Apple 对字典值的定义,由于键可能存在也可能不存在,因此从字典返回的任何值都是可选的

You can also use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary's subscript returns an optional value of the dictionary's value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key.

我正在尝试使用参数字典中的 auth_token 进行网络调用。

let params = ["auth_token" : authToken()]
print(params["auth_token"]) // shows Optional(dwadhuiwahd)

字典中的值不是可选的。我通过 authToken() 函数中的条件绑定(bind)并打印出来来检查这一点。但是,当打印出保存 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

关于ios - Alamofire 使用带有字典参数的可选值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38880197/

相关文章:

ios - 在滚动条上隐藏 UINavigationBar

ios - 如何找到字典数组中 'name' 键以某个字母开头的第一个索引?

iOS Swift MapKit 使注释可由用户拖动?

swift - 游戏中心匹配始终无效

ios - 从类型 '(_, _) throws -> ()' 的抛出函数到非抛出函数类型 '(JSON?, Error?) -> Void' 的无效转换

ios - 如何从 URL 加载图像并将其显示在 tableView 单元格中 (Swift 3)

ios - 接收 int 类型的集合元素不是 iOS 中的 objective-c 对象

objective-c - 将代码从 Objective-C 转换为 Swift 问题

ios - 页面控件 UITableView Swift

ios - Alamofire 后台服务,全局经理?全局授权 header ?