使用AFNetworking进行网络请求,请求失败时无法直接看到返回错误信息,需要从返回的错误集合中找出我们需要的信息,转换成可见形式。
/**
## Error Domains
The following error domain is predefined.
- `NSString * const AFURLResponseSerializationErrorDomain`
### Constants
`AFURLResponseSerializationErrorDomain`
AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
*/
FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain;
/**
## User info dictionary keys
These keys may exist in the user info dictionary, in addition to those defined for NSError.
- `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
- `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey`
### Constants
`AFNetworkingOperationFailingURLResponseErrorKey`
The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
`AFNetworkingOperationFailingURLResponseDataErrorKey`
The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey;
NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response";
NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response";
NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data";
let request = netManager.post("https://xx.com/api", parameters: requestData, headers : nil, progress:nil,success: {(task, data) in
var dictionary = NSDictionary()
if data is NSDictionary {
dictionary = data as! NSDictionary
}else if data is Data {
do{
dictionary = try JSONSerialization.jsonObject(with: data as! Data, options: JSONSerialization.ReadingOptions.fragmentsAllowed) as! NSDictionary
}catch{}
}
let resultCode = String(describing: (dictionary.value(forKey: "status") ?? "401")!)
if resultCode == "200" {
}else{
}
}){ (task, error) in
do {
let data = (error as NSError).userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey]
let sData = try JSONSerialization.jsonObject(with: data as! Data, options: JSONSerialization.ReadingOptions.fragmentsAllowed)
print("fetchsession fail , sData = \(sData)")
}catch{
print("fetchsession exception error \(error)")
}
}