import UIKit import Photos @available(iOS 8.0, *) class CustomAblum: NSObject { static let sharedInstance = CustomAblum() var assetCollection: PHAssetCollection! var albumFound : Bool = false var photosAsset: PHFetchResult! var collection: PHAssetCollection! var assetCollectionPlaceholder: PHObjectPlaceholder! static let albumName = "扫描图片" override init() { super.init(); self.createAlbum() } private func createAlbum() { let fetchOptions = PHFetchOptions() fetchOptions.predicate = NSPredicate(format: "title = %@",CustomAblum.albumName); let collection : PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions) if let _: AnyObject = collection.firstObject { self.albumFound = true assetCollection = collection.firstObject as! PHAssetCollection } else { PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let createAlbumRequest : PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(CustomAblum.albumName); self.assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection }, completionHandler: { success, error in self.albumFound = (success ? true: false) if (success) { let collectionFetchResult = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([self.assetCollectionPlaceholder.localIdentifier], options: nil) print(collectionFetchResult) self.assetCollection = collectionFetchResult.firstObject as! PHAssetCollection } }) } } func saveImage(image: UIImage) { if self.assetCollection != nil { PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image) let assetPlaceholder = assetChangeRequest.placeholderForCreatedAsset let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection) albumChangeRequest?.addAssets([assetPlaceholder!]) }, completionHandler: nil) } } }
使用时直接掉saveImage方法。
时间: 2024-11-12 18:53:05