在info.plist中添加权限
保存Xcode中导入的图片
在info.plist中添加权限
Privacy - Photo Library Usage Description
// 使用
@State var imageName = "Xcode中导入的图片名"
saveImage(imageName: imageName)
下载Xcode中的图片
import Photos
func saveImage(imageName: String) {
guard let image = UIImage(named: imageName) else {
print("Image not found!")
return
}
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
if PHPhotoLibrary.authorizationStatus() != .authorized {
PHPhotoLibrary.requestAuthorization { status in
if status == .authorized {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
}
}
}
保存网络图片
在info.plist中添加权限
Privacy - Photo Library Usage Description
func downLoad(){
let urlString: String = "https://img0.baidu.com/it/u=1058961982,3919091402&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9622de18364605eae71720edd72f249/"
guard let url = URL(string:urlString) else { return }
let data = NSData(contentsOf: url)
let image : UIImage = UIImage.init(data: data! as Data)!
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
保存网络视频
在info.plist中添加权限
Privacy - Photo Library Usage Description
// 使用
VideoDownloadManager.shared.startDownload(videoURL: "https://www.w3schools.com/html/movie.mp4"
下载视频
import Foundation
import UIKit
class VideoDownloadManager: UIViewController {
static let shared = VideoDownloadManager()
var inDownload = false
override func viewDidLoad() {
super.viewDidLoad()
}
func startDownload(videoURL: String) {
if inDownload == true {
print("有视频正在下载中...")
return
}
let session = URLSession.init(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
let downloadTask = session.downloadTask(with: URL(string: videoURL)!)
downloadTask.resume()
inDownload = true
print("视频保存中...")
}
}
extension VideoDownloadManager: URLSessionDelegate, URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let cache = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last
let file: String = cache?.appending(downloadTask.response?.suggestedFilename ?? "") ?? ""
do {
try FileManager.default.moveItem(at: location, to: URL.init(fileURLWithPath: file))
} catch let error {
print(error)
}
let videoCompatible = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(file)
if videoCompatible {
UISaveVideoAtPathToSavedPhotosAlbum(file, self, #selector(didFinishSavingVideo(videoPath:error:contextInfo:)), nil)
} else {
print("该视频无法保存至相册")
}
}
@objc private func didFinishSavingVideo(videoPath: String, error: NSError?, contextInfo: UnsafeMutableRawPointer?) {
inDownload = false
if error != nil {
print("保存视频失败")
} else {
print("视频已保存")
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
}
}