错误 Alamofire 5 响应成功和响应失败

Posted

技术标签:

【中文标题】错误 Alamofire 5 响应成功和响应失败【英文标题】:Error Alamofire 5 response success and response failure 【发布时间】:2020-05-12 23:29:59 【问题描述】:

我使用的是版本 4 的 Alamofire,它运行良好。当我将 Alamofire 更新到版本 5 时,我在获取结果响应“.success”或“.failure”时出错

如何使用 Alamofire 5 获得结果响应“.success”或“.failure”?

AF.upload(multipartFormData:  multipartFormData in

            multipartFormData.append(imgData!, withName: "signature", fileName: String("signature"), mimeType: "image/jpg")

            for (key, value) in parameters 
                multipartFormData.append((value.data(using: String.Encoding.utf8)!), withName: key)
            
        ,
        to: URL,
        method: .post,
        headers: headers)  (result) in
            switch result 
            case .success(let upload, _, _):

                upload.uploadProgress(closure:  (progress) in
                    print("Upload Progress: \(progress.fractionCompleted)")
                )

                upload.responseJSON  response in
                    print("Succes: ", response.result.value ?? "")
                    if let data = response.data 
                        do 
                            let decoder = JSONDecoder()
                            let model = try decoder.decode(T.self, from: data)
                            success(model)
                         catch let error as NSError 
                            print(error)
                        
                    
                
            case .failure(let encodingError):
                print("error: ", encodingError)
            
        

【问题讨论】:

上述问题你得到解决方案了吗? 【参考方案1】:

在 Alamofire 5.0 中,为什么需要成功和失败?我用下面的代码实现它

  static func uploadFile(url: String, fileData: Data?, parameters: [String : String], type: MessageType!, fileName: String!, completionHandler: @escaping (Result<Data, Error>) -> Void) 

        _ = AF.upload(multipartFormData:  (multiFormData) in
            var fileType: String!
            if type! == MessageType.Video 
                fileType = "video/mp4"
             else if type! ==  MessageType.Image 
                fileType = "image/jpeg"
            
            multiFormData.append(fileData!, withName: "uploadedfile", fileName: fileName , mimeType: fileType)
            for (key, value) in parameters 
                multiFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            
        , to: url).uploadProgress(queue: .main, closure:  progress in
            print("Upload Progress: \(progress.fractionCompleted)")
        ).responseJSON(completionHandler:  response in
            if response.error != nil 
                completionHandler(.failure(response.error!))
             else 
                completionHandler(.success(response.data!))
            
        )



    

【讨论】:

【参考方案2】:

几天前我遇到了同样的问题,这里是这个的工作代码。

pod 'Alamofire','5.1.0'

    AF.upload(multipartFormData:  (mulipartFormData) in
        for (key, value) in parameters 
            mulipartFormData.append(value.data(using: .utf8)!, withName: key)
        
        for (image, key) in images 
            let imgData = image.jpegData(compressionQuality: compression)!
            mulipartFormData.append(imgData, withName: key, fileName: "\(key).jpeg", mimeType: "image/jpeg")
        

    , to: url, method: .post, headers:  HTTPHeaders(headers)).response  response in

        onComplete(response.data, response.response, response.error)

    .uploadProgress  progress in

        print("progress: \(progress.fractionCompleted * 100)")
        onProgress?(progress)
    

【讨论】:

【参考方案3】:

要确定请求是否成功,使用 AF 5,您可以在响应块中执行此操作(response、responseData、responseJSON、...):

switch response.result 
case .success:
    // get the data
case .failure:
    // error

或者只是检查:

response.value != nil

【讨论】:

以上是关于错误 Alamofire 5 响应成功和响应失败的主要内容,如果未能解决你的问题,请参考以下文章

请求失败时从 AlamoFire 获取 JSON 响应

iOS Swift 2 - 失败时的 Alamofire 打印响应值

如何快速修复成功和失败案例的 Alamofire 5 错误?

在 swift 中使用 Alamofire 的 JsonSerialization 错误

Alamofire 5.0.0-rc.3 RequestInterceptor Adapt 方法没有被调用 Alamofire 虽然在响应中有任何错误时会调用重试

如何在 swift 中在 alamofire 中打印错误 html?