gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:38:39 27 4
gpt4 key购买 nike

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

1 Multiple images uploaded successfully with this code.

2 I am using TLPHAsset for image/video selection.

注意:文字上传成功,仅视频未上传。我已成功收到回复。

这是我的示例代码

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

最佳答案

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

关于ios - 使用 alamofire 5 Swift 5 将视频上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56785274/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com