「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
}

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

相关推荐
碎_浪4 小时前
Mac 壁纸被 MDM 锁住?我做了个 2MB 的开源方案
macos·开源·swift
小牛不牛的程序员1 天前
开源一个 macOS 剪贴板「意图识别」工具——不只是存储,更是理解你复制了什么
macos·swift
apihz2 天前
经纬度制作高清卫星图片免费 API 接口详解
开发语言·ios·swift
00后程序员张3 天前
iOS 打包方式汇总 从 Xcode Archive 到轻量级工具链的 IPA 构建
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
sweet丶4 天前
Swift 黑魔法:`@dynamicMemberLookup`
swift·rxswift
大熊猫侯佩4 天前
SwiftUI 侦探笔记:iPhone 14 失踪的“刘海”与侯佩的像素诡计
swiftui·swift·apple
大熊猫侯佩4 天前
WWDC26 新 @ContentBuilder 修饰符:SwiftUI 终于有了户口本
swiftui·swift·wwdc
东坡肘子4 天前
当 Linux 成为“空气”:容器、Agent 与不再重要的“桌面之争” -- 肘子的 Swift 周报 #143
人工智能·swiftui·swift
wabil6 天前
【LVGL】滑动切换页面的界面优化实践
开发语言·ios·swift
东坡肘子11 天前
SPI 加入 Apple,Swift 迈向自举 -- 肘子的 Swift 周报 #142
人工智能·swiftui·swift