同样的代码在iOS8下没有问题,iOS7就取不到数据(会包Cocoa Error 3840之类的错误),跟踪发现请求Head参数设置不管用,根据文字底部的参考改了一下兼容代码:
private func getRequest(method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil) -> NSMutableURLRequest {
let request = NSMutableURLRequest(URL: NSURL( string: URLString.URLString)!)
request.HTTPMethod = method.rawValue
if parameters != nil {
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters!, options: nil, error: nil)
}
request.setValue(API_UA, forHTTPHeaderField: " User-Agent ")
request.setValue(HEADER_ACCEPT, forHTTPHeaderField: " Accept ")
request.setValue( " application/json ", forHTTPHeaderField: " Content-Type ")
return request
}
let request = NSMutableURLRequest(URL: NSURL( string: URLString.URLString)!)
request.HTTPMethod = method.rawValue
if parameters != nil {
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters!, options: nil, error: nil)
}
request.setValue(API_UA, forHTTPHeaderField: " User-Agent ")
request.setValue(HEADER_ACCEPT, forHTTPHeaderField: " Accept ")
request.setValue( " application/json ", forHTTPHeaderField: " Content-Type ")
return request
}
这里API_UA和HEADER_ACCEPT更改为自己的Head参数即可,使用代码:
var request: Request!
if DeviceUtils.isIOS7() {
request = mHttpManager.request(getRequest(method, URLString, parameters: parameters))
} else {
request = mHttpManager.request(method, URLString , parameters: parameters, encoding: ParameterEncoding.JSON)
}
// request.responseJSON....
if DeviceUtils.isIOS7() {
request = mHttpManager.request(getRequest(method, URLString, parameters: parameters))
} else {
request = mHttpManager.request(method, URLString , parameters: parameters, encoding: ParameterEncoding.JSON)
}
// request.responseJSON....
代码说明:
a)、 mHttpManager就是Manager.sharedInstance,注意别忘了设置mHttpManager.session.configuration.HTTPAdditionalHeaders,在iOS8下还是管用的
参考:
Setting Custom HTTP Headers in Alamofire in iOS 7 not working
(参考帖子,也尝试设置NSURLSessionConfiguration但是没有效果)
本文转自博客园农民伯伯的博客,原文链接:【iOS】Alamofire库在iOS7下设置Head无效的问题,如需转载请自行联系原博主。