「Swift」保存图片至相册

前言:需要将图片下载至本地相册
使用到的三方库:
swift 复制代码
TZImagePickerController
SVProgressHUD

实现步骤:

1.新增App权限:需获取相册读写权限

在info.plist中添加以下两个权限和相应的Key值

Privacy - Photo Library Additions Usage Description(相册写入权限)

Privacy - Photo Library Usage Description(相册读取权限)

2.代码实现获取相册权限:
swift 复制代码
	private func initView() {
        self.view.backgroundColor = UIColor.white
        self.title = "保存图片"
        
        imageView = UIImageView(image: UIImage.image(.fruit_mango))
        
        let tapImageView = UITapGestureRecognizer(target: self, action: #selector(tapImageView))
        imageView.addGestureRecognizer(tapImageView)
        imageView.isUserInteractionEnabled = true
        
        self.view.addSubview(imageView)
        
        imageView.snp.makeConstraints { make in
            make.top.equalTo(Common.navigatorHeight + 20.fit())
            make.left.equalTo(20.fit())
            make.right.equalTo(-20.fit())
            make.height.equalTo(Common.screenWidth - 40.fit())
        }
    }

    
    @objc
    private func tapImageView() {
        let authorizationStatus = PHPhotoLibrary.authorizationStatus()
        
        if authorizationStatus == .notDetermined {
            /// 首次保存 权限未知 需进行相册权限授权操作
            PHPhotoLibrary.requestAuthorization { status in
                if status == .authorized {
                    if let image = self.imageView.image {
                        self.saveImage(image: image)
                    }
                    
                } else {
                    self.alertUser(message: "请在iPhone的"设置--隐私--相册"选项中,允许此App访问你的相册。")
                }
            }
            
        } else if authorizationStatus == .authorized {
            /// 权限允许
            if let image = self.imageView.image {
                self.saveImage(image: image)
            }
            
        } else {
            /// 权限不允许
            self.alertUser(message: "请在iPhone的"设置--隐私--相册"选项中,允许此App访问你的相册。")
        }
   }
3.保存图片功能实现:
swift 复制代码
private func saveImage(image: UIImage) {
     let imageManager = TZImageManager()
     imageManager.savePhoto(with: image) { asset, error in
         if asset != nil {
             SVProgressHUD.showSuccess(withStatus: "保存成功")
         }
         
         if error != nil {
             SVProgressHUD.showError(withStatus: "保存失败")
         }
     }
 }
4.其余补充代码:
swift 复制代码
/// 弹窗提示
private func alertUser(message: String) {
     let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
     alert.addAction(UIAlertAction(title: "设置", style: UIAlertAction.Style.default, handler: { (_) in
         DispatchQueue.main.async {
             self.openApplicationSetting()
         }
     }))
     alert.addAction(UIAlertAction(title: "知道了", style: UIAlertAction.Style.cancel, handler: nil))
     present(alert, animated: true, completion: nil)
}
 
/// 打开设置
func openApplicationSetting() {
     if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
         UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
     }
}

效果图:


补充:获取相册权限在iOS14版本后有更新的方法,更加清晰了需要获取onlyadd还是readWrite权限,如果只需添加图片的话仅获取onlyadd权限即可,在info.plist中仅添加相册写入权限和相应的Key值即可,但由于App的受众人群更广,通常会采用上述方法实现

新方法相关代码:
swift 复制代码
if #available(iOS 14, *) {
    PHPhotoLibrary.requestAuthorization(for: .readWrite) { status in
        if status == .authorized {
            if let image = self.imageView.image {
                self.saveImage(image: image)
            }
            
        } else {
            self.alertUser(message: "请在iPhone的"设置--隐私--相册"选项中,允许此App访问你的相册。")
        }
    }
} else {
    // Fallback on earlier versions
}

整理不易,望大家多多点赞,谢谢大家!

相关推荐
Swift社区2 天前
Swift LeetCode 246 题解:中心对称数(Strobogrammatic Number)
开发语言·leetcode·swift
Lexiaoyao202 天前
SwiftUI 字体系统详解
swiftui·swift
YungFan2 天前
Swift 6.1 新特性
swift
Invisible_He4 天前
iOS自定义collection view的page size(width/height)分页效果
ui·ios·swift·collection
无知的前端4 天前
iOS性能优化:OC和Swift实战指南
ios·性能优化·swift
JQShan4 天前
为什么 Swift 的反射像个“玩具”?聊聊 Mirror 背后的设计哲学
面试·swift·设计
东坡肘子4 天前
MCP 崛起与苹果的 AI 框架设想 | 肘子的 Swift 周报 #077
人工智能·swiftui·swift
YungFan5 天前
SwiftUI-国际化
ios·swiftui·swift
xinxiyinhe6 天前
Swift语音助手(苹果生态系统的核心编程语言)
人工智能·swift
潜龙95278 天前
第2.5节 iOS 覆盖率数据的采集
ios·swift·覆盖率