我正在 Swift 中开发视频编辑应用程序。我正在使用 Progress 下载视频剪辑。
我的问题是,当我使用 Alamofire 下载视频时,这会卡住我的 UI,直到该过程完成。这是我的代码:
//MARK: - Download Video file
func downloadVideoFileFromUrl(videoUrl: URL, video: VideoFileModel) {
var uniqueVideoID = ""
var uniqueID = ""
uniqueID = video.fileID
uniqueVideoID = uniqueID + ".MOV"
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
// the name of the file here I kept is yourFileName with appended extension
documentsURL.appendPathComponent(uniqueVideoID)
return (documentsURL, [.removePreviousFile])
}
var vidProgress: Float = 0.0
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 900
manager.session.configuration.timeoutIntervalForResource = 900
manager.download(videoUrl, to:destination)
.downloadProgress { (progress) in
DispatchQueue.main.async(execute: {
vidProgress = Float(progress.fractionCompleted)
video.downloadFromUrlProgress = vidProgress
//post notification
let userInfo = [ "videoFileModel" : video]
NotificationCenter.default.post(name: Notification.Name(rawValue: "VideoDownloadProgress"), object: nil, userInfo: userInfo)
})
}
.response { defaultDownloadResponse in
DispatchQueue.main.async(execute: {
print(defaultDownloadResponse.destinationURL as Any)
if defaultDownloadResponse.destinationURL != nil{
video.localFilePath = (defaultDownloadResponse.destinationURL?.absoluteString)!
video.downloadFromUrlProgress = 1
video.isVideoDownload = true
let userInfo = [ "videoFileModel" : video]
NotificationCenter.default.post(name: Notification.Name(rawValue: "VideoDownloadProgress"), object: nil, userInfo: userInfo)
print("Completed!")
}
})
}
}
我正在使用
调用此方法DispatchQueue.global(qos: .userInitiated).sync { }
谁能帮我解决这个问题吗?
最佳答案
尝试使用以下代码:
func download(url: String,fileName: String,progressUpdate: ((_ percent: Double) -> Void)? = nil, completion:@escaping (_ success: Bool, _ error: Error?,_ fileUrl: URL?) -> Void) {
let utilityQueue = DispatchQueue.global(qos: .utility)
Alamofire.download(url)
.downloadProgress(queue: utilityQueue) { progress in
DispatchQueue.main.async {
progressUpdate?(progress.fractionCompleted)
}
}
.responseData { response in
if let data = response.result.value {
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(fileName)
do {
try data.write(to: fileURL, options: .atomic)
completion(true,nil,fileURL)
} catch {
completion(false,error,nil)
}
}
}
}
如何使用:
download(url: "", fileName: "filName", progressUpdate: { (progress) in
print("Progress \(progress)")
}) { (success, error, filePath) in
print("success \(success) error \(error?.localizedDescription ?? "nil") path \(filePath?.absoluteString ?? "nil")")
}
关于ios - 使用 Alamofire 下载视频会卡住 Swift iOS 中的 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56847451/