在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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:
|
请发表评论