声明
欢迎转载,但请保留文章原始出处:)
博客园:http://www.cnblogs.com
农民伯伯: http://over140.cnblogs.com
正文
同样的代码在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,继续swift,继续遇到问题解决问题。