Photokit保存GIF图片

2020/3/12 posted in  iOS开发 总阅读量

最近开发的过程中遇到了需要保存GIF图片到相册的需求,网上找到的都是使用ALAssetsLibrary库的方法,iOS 9.0以后已放弃使用,推荐使用Photos库来操作。代码如下:

if imgStr.hasSuffix("gif") { // GIF图片
    let session = URLSession(configuration: URLSessionConfiguration.default)
                
    let task = session.dataTask(with: URL(string: imgStr)!) { (imgData, _, error) in
        if error != nil {
            SVProgressHUD.showError(withStatus: "保存失败")
            return
        }
                    
        guard let data = imgData else { return }
                    
        PHPhotoLibrary.shared().performChanges({
            let options = PHAssetResourceCreationOptions()
            PHAssetCreationRequest.forAsset().addResource(with: .photo, data: data, options: options)}) { (success, error) in
                if success {
                    SVProgressHUD.showSuccess(withStatus: "已保存到相册")
                } else {
                    SVProgressHUD.showInfo(withStatus:error?.localizedDescription)
                }
            }
        }
    }      
    task.resume()
}