AFNetworking 2.0 AFHTTPSessionManager: how to get status code and response JSON in failure block?

后端 未结 7 802
你的背包
你的背包 2020-12-04 10:08

When switched to AFNetworking 2.0 the AFHTTPClient has been replaced by AFHTTPRequestOperationManager / AFHTTPSessionManager (as mentioned in the migration guide). The very

7条回答
  •  悲&欢浪女
    2020-12-04 10:46

    In Swift 2.0 (in case you cannot use Alamofire yet):

    Get status code:

    if let response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey] as? NSHTTPURLResponse {
        print(response.statusCode)
    }
    

    Get response data:

    if let data = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? NSData {
        print("\(data.length)")
    }
    

    Some JSON REST APIs return error messages in their error responses (Amazon AWS services for example). I use this function to extract the error message from an NSError that has been thrown by AFNetworking:

    // Example: Returns string "error123" for JSON { message: "error123" }
    func responseMessageFromError(error: NSError) -> String? {
        do {
            guard let data = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? NSData else {
                return nil
            }
            guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String: String] else {
                return nil
            }
            if let message = json["message"] {
                return message
            }
            return nil
        } catch {
            return nil
        }
    }
    

提交回复
热议问题