使用alamofire 5 Swift 5将视频上传到服务器

时间:2019-06-27 06:38:20

标签: ios swift alamofire

我需要帮助,使用alamofire 5将视频上传到服务器上

  

1使用此代码成功上传了多张图片。

     

2我正在使用TLPHAsset进行图像/视频选择。

注意:文本上传成功,仅视频未上传。我收到了成功的回应。

这是我的示例代码

func apiCallWithMultipart(arrMedia:[TLPHAsset], completionHandler: @escaping (DataResponse<Any>) -> Void) {


    if VVSingleton.sharedInstance.isReachable {
        // Show HUD
        VVSingleton.sharedInstance.showHUDWithText(strText: "Please wait...")
        //            VVSingleton.sharedInstance.showHUDWithText(strText: "Loading \(url.absoluteString.split(separator: "/").last ?? "")")

        headers = createHeadersMultipart()

        DispatchQueue.main.async {
            AF.upload(multipartFormData: { (multipartFormData) in
                // Add parameters
                for (key, value) in self.parameters {
                    let paramValue = "\(value)" as String
                    multipartFormData.append(paramValue.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: key as String)
                }

                for media in arrMedia {
                    if media.type == TLPHAsset.AssetType.video {
                        media.phAsset?.requestContentEditingInput(with: PHContentEditingInputRequestOptions(), completionHandler: { (phContentEditingInput, [AnyHashable : Any]) in

                            if let videoURL = (phContentEditingInput!.audiovisualAsset as? AVURLAsset)?.url {
                                if videoURL.isFileURL {

//                                        do {
//                                            let videoData = try Data(contentsOf: videoURL, options: .mappedIfSafe)
//                                            print(videoData)
//                                            //  here you can see data bytes of selected video, this data object is upload to server by multipartFormData upload
//                                            multipartFormData.append(videoData, withName: "album_files[]", fileName: media.originalFileName, mimeType: media.MIMEType(videoURL))
//                                        } catch  {
//                                            print("error while create data = \(error)")
//                                        }


                                    //print("\(videoURL)" + media.originalFileName!)
                                    multipartFormData.append(videoURL, withName: "album_files[]", fileName: media.originalFileName ?? "Sample", mimeType: media.MIMEType(videoURL)!)

                                    //multipartFormData.append(videoURL, withName: "unicorn")
                                }
                            }
                        })
                    }
                    else if media.type == TLPHAsset.AssetType.photo {
                        let imageData = media.fullResolutionImage?.jpegData(compressionQuality: 1)
                        if let data = imageData {
                            multipartFormData.append(data, withName: "album_files[]", fileName: "\(Date().timeIntervalSince1970).jpg", mimeType: MimeType_jpg)
                        }
                    }
                }



            }, usingThreshold: UInt64.init(), fileManager: FileManager.default, to: self.url, method: HTTPMethod.post, headers: self.headers)


                .uploadProgress { progress in // main queue by default
                    print("Upload Progress: \(progress.fractionCompleted)")
                    print("Upload Estimated Time Remaining: \(String(describing: progress.estimatedTimeRemaining))")
                    print("Upload Total Unit count: \(progress.totalUnitCount)")
                    print("Upload Completed Unit Count: \(progress.completedUnitCount)")
                }

                .responseJSON { (response) in
                    // Error Handle : https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling

                    //            #file          String   The name of the file in which it appears.
                    //            #line          Int      The line number on which it appears.
                    //            #column        Int      The column number in which it begins.
                    //            #function      String   The name of the declaration in which it appears.
                    //            #dsohandle     String   The dso handle.
                    print("\n\n\nFile -> \(#file), Function -> \(#function), Line -> \(#line)\n")
                    print("Request: \(String(describing: response.request))")   // original url request
                    print("Parameters: \(self.parameters.description)")   // original url request
                    //print("Response: \(String(describing: response.response))") // http url response
                    //print("Result: \(response.result)")                         // response serialization result

                    if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                        print("String Data: \(utf8Text)") // original server data as UTF8 string
                    }

                    if let json = response.value {
                        print("JSON Response : \(json)") // serialized json response
                    }

                    // Hide HUD
                    //                    DispatchQueue.main.asyncAfter(deadline: .now()) {
                    // your code here
                    if Thread.isMainThread {
                        VVSingleton.sharedInstance.hideHUD()
                    }
                    else {
                        DispatchQueue.main.async {
                            VVSingleton.sharedInstance.hideHUD()
                        }
                    }

                    completionHandler(response)
            }
        }
    } else {
        // Show Network error
        VVSingleton.sharedInstance.showAlertMessage(TitleString: "Network Error", AlertMessage: "Your device is not connected to the Internet", viewController: delegate)
    }
}

上传进度日志

Upload Progress: 1.0
Upload Estimated Time Remaining: nil
Upload Total Unit count: 885
Upload Completed Unit Count: 885

1 个答案:

答案 0 :(得分:0)

您应该为视频添加Data类型,使用Alamofire发送多部分请求时,请尝试以下操作:

    do {
        let videoData = try Data(contentsOf: videoURL)
        multipartFormData.append(videoData, withName: "album_file", fileName: "album_file", mimeType: "mp4")
    } catch {
        debugPrint("Couldn't get Data from URL: \(videoUrl): \(error)")
    }