如何在 Alamofire 4.0 中添加带有上传进度百分比的标签的进度条

Posted

技术标签:

【中文标题】如何在 Alamofire 4.0 中添加带有上传进度百分比的标签的进度条【英文标题】:How I can add progress bar with label with percentage of progress of upload in Alamofire 4.0 【发布时间】:2016-12-31 12:01:18 【问题描述】:

我正在尝试通过 Alamofire 4.0 将视频上传到服务器,我想添加进度条以显示上传过程中上传过程的百分比,我如何通过与 Alamofire 上传相同的功能来做到这一点。

我的上传功能代码:

Alamofire.upload(multipartFormData:  multipartFormData in



                        multipartFormData.append(url.absoluteURL!, withName: "videoFile", fileName: "alaa", mimeType: "mov")
                        multipartFormData.append("video".data(using: .utf8)!, withName: "load")
                        multipartFormData.append("record".data(using: .utf8)!, withName: "type")


                    , with: URL, encodingCompletion:  (result) in
                        // code
                        print("uploaded")
                    )

【问题讨论】:

【参考方案1】:

直接引用 AlamoFire 文档:

上传进度

当您的用户等待上传完成时,有时它 可以方便地向用户显示上传进度。任何 UploadRequest 可以同时报告上传进度和下载进度 使用 uploadProgress 和 downloadProgress API 的响应数据。

let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")

Alamofire.upload(fileURL, to: "https://httpbin.org/post")
    .uploadProgress  progress in // main queue by default
        print("Upload Progress: \(progress.fractionCompleted)")
    
    .downloadProgress  progress in // main queue by default
        print("Download Progress: \(progress.fractionCompleted)")
    
    .responseJSON  response in
        debugPrint(response)
    

【讨论】:

这一行视频的网址在哪里? let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") 意思是在你的主包中获取一个名为 video.mov 的文件的 URL。 这是示例代码,而不是特定于您的问题的代码。该行为来自应用程序包的名为“video.mov”的文件创建了一个文件 url。 @DuncanC 你知道 downloadProgress 在这个例子中做了什么吗?找了一阵子,看了看AlamoFire的代码,想不通。是服务器响应的下载进度吗?【参考方案2】:

请检查。

            var imgData = Data()
            if image != nil 

                imgData = UIImageJPEGRepresentation(image!, 1.0)!
            

            Alamofire.upload(multipartFormData: multipartFormData in
                multipartFormData.append(imgData, withName: "image", fileName: "imagefilename", mimeType: "image/jpeg")

                for (key, value) in param 

                    //let data = (value as! String).data(using: String.Encoding.utf8)!
                    let data = (value as AnyObject).data(using: String.Encoding.utf8.rawValue)
                    multipartFormData.append(data!, withName: key as! String)
                
            ,
                             usingThreshold:UInt64.init(),
                             to:fullLink,
                             method:.post,
                             headers:[:],
                             encodingCompletion:  encodingResult in

                                switch encodingResult 

                                case .success(let upload, _, _):

                                    upload.uploadProgress  progress in // main queue by default

                                        print("Upload Progress: \(progress.fractionCompleted)")
                                    

                                    upload.responseJSON  response in

                                        debugPrint(response)

                                        if let TempresponseDict:NSDictionary = response.result.value as? NSDictionary 

                                            if (TempresponseDict.object(forKey: "response") as? String)?.caseInsensitiveCompare("success") == .orderedSame 

                                                CompletionHandler(true, TempresponseDict)
                                            
                                            else 

                                                var statusCode = response.response?.statusCode

                                                if let error = response.result.error as? AFError 

                                                    statusCode = error._code // statusCode private

                                                    switch error 

                                                    case .invalidURL(let url):
                                                        print("Invalid URL: \(url) - \(error.localizedDescription)")
                                                    case .parameterEncodingFailed(let reason):
                                                        print("Parameter encoding failed: \(error.localizedDescription)")
                                                        print("Failure Reason: \(reason)")
                                                    case .multipartEncodingFailed(let reason):
                                                        print("Multipart encoding failed: \(error.localizedDescription)")
                                                        print("Failure Reason: \(reason)")
                                                    case .responseValidationFailed(let reason):
                                                        print("Response validation failed: \(error.localizedDescription)")
                                                        print("Failure Reason: \(reason)")

                                                        switch reason 

                                                        case .dataFileNil, .dataFileReadFailed:
                                                            print("Downloaded file could not be read")
                                                        case .missingContentType(let acceptableContentTypes):
                                                            print("Content Type Missing: \(acceptableContentTypes)")
                                                        case .unacceptableContentType(let acceptableContentTypes, let responseContentType):
                                                            print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)")
                                                        case .unacceptableStatusCode(let code):
                                                            print("Response status code was unacceptable: \(code)")
                                                            statusCode = code
                                                        
                                                    case .responseSerializationFailed(let reason):

                                                        print("Response serialization failed: \(error.localizedDescription)")
                                                        print("Failure Reason: \(reason)")
                                                        // statusCode = 3840 ???? maybe..
                                                    

                                                    print("Underlying error: \(error.underlyingError)")
                                                
                                                else if let error = response.result.error as? URLError 

                                                    print("URLError occurred: \(error)")
                                                
                                                else 

                                                    print("Unknown error: \(response.result.error)")
                                                

                                                print("\(statusCode)") // the status code

                                                CompletionHandler(false, TempresponseDict)
                                            
                                        
                                        else 

                                            CompletionHandler(false, NSDictionary())
                                        
                                    

                                case .failure(let encodingError):

                                    print(encodingError)
                                    CompletionHandler(false, NSDictionary())
                                
            )
        

【讨论】:

fullLink 我必须把它作为字符串或 urlrequest 因为在第二种情况下它给我 null 所以视频不会上传 ,这部分我不明白,如果我有 2 个参数,如上面的代码,我该如何处理。 for (key, value) in param //let data = (value as!String).data(using: String.Encoding.utf8)! let data = (value as AnyObject).data(using: String.Encoding.utf8.rawValue) multipartFormData.append(data!, withName: key as!String) fullLink = String for (key, value) in param //let data = (value as!String).data(using: String.Encoding.utf8)! let data = (value as AnyObject).data(using: String.Encoding.utf8.rawValue) multipartFormData.append(data!, withName: key as!String) 你的场景不需要这段代码。 您可以用您的数据将此行写入 2 次。 multipartFormData.append(imgData, withName: "image", fileName: "imagefilename", mimeType: "image/jpeg")

以上是关于如何在 Alamofire 4.0 中添加带有上传进度百分比的标签的进度条的主要内容,如果未能解决你的问题,请参考以下文章