前言:需要将图片下载至本地相册
使用到的三方库:
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
}
整理不易,望大家多多点赞,谢谢大家!