美文网首页
Swift 保存图片/视频到手机相册

Swift 保存图片/视频到手机相册

作者: 麦志超 | 来源:发表于2023-08-08 10:03 被阅读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)
                        }
                    }
                }
            }
        }
    

    相关文章

      网友评论

          本文标题:Swift 保存图片/视频到手机相册

          本文链接:https://www.haomeiwen.com/subject/ccynpdtx.html