【问题标题】:Uploading video to server with alamofire 5 Swift 5使用 alamofire 5 Swift 5 将视频上传到服务器
【发布时间】:2019-11-09 03:15:05
【问题描述】:

我需要帮助才能使用 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

【问题讨论】:

  • 对象videoURL的类型是什么?它应该是Data,但顾名思义,它是URL。尝试获取对视频数据的引用,并将其传递给multipartFormData.append(...)
  • 这是我的视频网址:file:///var/mobile/Media/DCIM/100APPLE/IMG_0101.MOV
  • Alamofire 不会将文件转换为数据。我不知道为什么,如果您对此有任何解决方案,请告诉我。

标签: ios swift alamofire


【解决方案1】:

您应该为您的视频添加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)")
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-11
    • 2017-02-13
    • 2016-06-09
    • 2018-01-19
    • 2016-06-07
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    相关资源
    最近更新 更多