标签:nop ali 验证 save oca sel ima creat 操作
1.info中写上
<key>NSCameraUsageDescription</key> <string>需要您的同意才能读取媒体资料库</string> <key>NSLocationWhenInUseUsageDescription</key> <string>需要您的同意才能读取媒体资料库</string> <key>NSPhotoLibraryUsageDescription</key> <string>需要您的同意才能读取媒体资料库</string> <key>Privacy - Photo Library Usage Description</key> <string>需要您的同意才能读取媒体资料库</string>
2.保存
import Photos //操作结果枚举 enum PhotoAlbumUtilResult { case success, error, denied } //相册操作工具类 class PhotoAlbumUtil: NSObject { public typealias completion = ((_ result: PhotoAlbumUtilResult) -> ()) //判断是否授权 class func isAuthorized() -> Bool { return PHPhotoLibrary.authorizationStatus() == .authorized || PHPhotoLibrary.authorizationStatus() == .notDetermined } //保存图片到相册 class func saveImageInAlbum(image: UIImage, albumName: String, completion: completion?) { //权限验证 if !isAuthorized() { completion?(.denied) return } var assetAlbum: PHAssetCollection? //如果指定的相册名称为空,则保存到相机胶卷。(否则保存到指定相册) if albumName.isEmpty { let list = PHAssetCollection .fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil) assetAlbum = list[0] } else { //看保存的指定相册是否存在 let list = PHAssetCollection .fetchAssetCollections(with: .album, subtype: .any, options: nil) list.enumerateObjects({ (album, index, stop) in let assetCollection = album if albumName == assetCollection.localizedTitle { assetAlbum = assetCollection stop.initialize(to: true) } }) //不存在的话则创建该相册 if assetAlbum == nil { PHPhotoLibrary.shared().performChanges({ PHAssetCollectionChangeRequest .creationRequestForAssetCollection(withTitle: albumName) }, completionHandler: { (isSuccess, error) in self.saveImageInAlbum(image: image, albumName: albumName, completion: completion) }) return } } //保存图片 PHPhotoLibrary.shared().performChanges({ //添加的相机胶卷 let result = PHAssetChangeRequest.creationRequestForAsset(from: image) //是否要添加到相簿 if !albumName.isEmpty { let assetPlaceholder = result.placeholderForCreatedAsset let albumChangeRequset = PHAssetCollectionChangeRequest(for: assetAlbum!) albumChangeRequset!.addAssets([assetPlaceholder!] as NSArray) } }) { (isSuccess: Bool, error: Error?) in if isSuccess { completion?(.success) } else{ print(error!.localizedDescription) completion?(.error) } } } }
3.使用
PhotoAlbumUtil.saveImageInAlbum(image: image, albumName: "APP") { (result) in DispatchQueue.main.async { switch result{ case .success: //"保存成功" break case .denied:
//没有权限,去设置里打开权限 let a = MyAlertController() a.addOKView("去设置"){ (a) in let url = URL(string: UIApplicationOpenSettingsURLString) if let url = url, UIApplication.shared.canOpenURL(url) { if #available(iOS 10, *) { UIApplication.shared.open(url, options: [:], completionHandler: { (success) in }) } else { UIApplication.shared.openURL(url) } } } a.addCancelView() a.show(self,title: "没有相册权限",message: "请您到 \"设置\" -> \"APP\" 开启相册权限", style: .alert ) break case .error: //"保存失败" } } }
标签:nop ali 验证 save oca sel ima creat 操作
原文地址:https://www.cnblogs.com/yyr0208/p/10260176.html