Swift 保存图片/视频到手机相册
2023-08-08 本文已影响0人
麦志超
1、保存图片
private func saveImage(image: UIImage) {
PHPhotoLibrary.shared().performChanges {
PHAssetChangeRequest.creationRequestForAsset(from: image)
} completionHandler: { isSuccess, error in
if isSuccess {
HUDTool.showMessage(L10n.saveSuccessfully)
} else {
HUDTool.showMessage(L10n.failToSave)
}
}
}
2、保存视频
private func saveVideo(url: URL) {
HUDTool.showWait(L10n.beSaving)
let fileName = "video_download_\(Int(Date().timeIntervalSince1970))"
let filePath = URL(fileURLWithPath: NSTemporaryDirectory() + "\(fileName).mp4")
MLog("filePath : \(filePath.absoluteString)")
let destination: DownloadRequest.Destination = { _, _ in
return (filePath, [.removePreviousFile, .createIntermediateDirectories])
}
AF.download(url, to: destination).response { _ in
DispatchQueue.main.async {
PHPhotoLibrary.shared().performChanges {
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: filePath)
} completionHandler: { isSuccess, error in
DispatchQueue.global(qos: .background).async {
if FileManager.default.fileExists(atPath: filePath.path) {
try? FileManager.default.removeItem(atPath: filePath.path)
}
}
if isSuccess {
HUDTool.showMessage(L10n.saveSuccessfully)
} else {
HUDTool.showMessage(L10n.failToSave)
}
}
}
}
}