Alamofire - 带有自定义标头的 Rest API 调用
Posted
技术标签:
【中文标题】Alamofire - 带有自定义标头的 Rest API 调用【英文标题】:Alamofire - Rest API call with Custom Header 【发布时间】:2018-05-16 12:10:13 【问题描述】:我正在使用 Swift + Alamofire。我正在使用一个以 JSON 格式返回数据的 Rest API,并且我已经在 Rest API 测试工具(即 PostMan)中对其进行了测试。这是它的快照,它工作正常
在这个 Get 请求中唯一的就是 Authorization Header。但是在 Swift+Alamofire 中同样不起作用。这里是代码 sn-p。
let requestHeaders: HTTPHeaders = [
"Authorization": "bearer " + (Session.user?.accessToken!)!
]
Alamofire.request("http://abcabc.com/api/StoreType/Stores", headers: requestHeaders).responseJSON (response) -> Void in
switch response.result
case .success:
guard let rawJson = response.result.value as? [String: Any] else
let serverError = NSError(domain: "Server error", code: (response.response?.statusCode)!, userInfo: ["msg": "Received Malformed data from server"])
errorBlock(serverError)
return
let formattedJson = JSON(rawJson)
if (formattedJson["Message"] != JSON.null)
let serverError = NSError(domain: "Server error", code: (response.response?.statusCode)!, userInfo: ["msg": formattedJson["Message"]])
errorBlock(serverError)
else // No error case
Session.storeCategories = StoreCategory.initializeStoreCategoriesWithStores(storeCategoryList: formattedJson)
successBlock(formattedJson)
case .failure(let error):
errorBlock(error)
但我总是收到以下错误。 (来自 Xcode 的快照)
【问题讨论】:
【参考方案1】:您的回复类型为 [[String: Any]]
而不是 [String: Any]
。
把它改成:
guard let rawJson = response.result.value as? [[String: Any]] else
let serverError = NSError(domain: "Server error", code: (response.response?.statusCode)!, userInfo: ["msg": "Received Malformed data from server"])
errorBlock(serverError)
return
【讨论】:
【参考方案2】:创建一个URLRequest
类型的自定义请求对象,在您的请求对象中设置您的URL
、Headers
和RequestType
,然后只需让Alamofire
启动此请求。
let requestHeaders: [String: String] = [
"Authorization": "bearer " + (Session.user?.accessToken!)!
]
if let url = URL(string: "https://www.example.com/someApiURL")
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.headerParam = requestHeaders
Alamofire.request(request).responseJSON (response) -> Void in
switch response.result
case .success:
guard let rawJson = response.result.value as? [String: Any] else
let serverError = NSError(domain: "Server error", code: (response.response?.statusCode)!, userInfo: ["msg": "Received Malformed data from server"])
errorBlock(serverError)
return
let formattedJson = JSON(rawJson)
if (formattedJson["Message"] != JSON.null)
let serverError = NSError(domain: "Server error", code: (response.response?.statusCode)!, userInfo: ["msg": formattedJson["Message"]])
errorBlock(serverError)
else // No error case
Session.storeCategories = StoreCategory.initializeStoreCategoriesWithStores(storeCategoryList: formattedJson)
successBlock(formattedJson)
case .failure(let error):
errorBlock(error)
【讨论】:
【参考方案3】:试试这个,对于来自 json 的响应类映射,您可以使用 Codable 或 ObjectMapper
var headers = ["":""]
headers["Authorization"] = "bearer " + (Session.user?.accessToken!)!
Alamofire.request(baseURL + endpoint,headers: headers)
.responseArray (response: DataResponse<[Model]>) in
print("Response: \(response)")
【讨论】:
以上是关于Alamofire - 带有自定义标头的 Rest API 调用的主要内容,如果未能解决你的问题,请参考以下文章