swiftUI 保存网络视频、网络图片和Xcode中导入的图片到手机相册

在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) {
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值