swift 将图片保存到自定义相册中
Posted Sunmair
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 将图片保存到自定义相册中相关的知识,希望对你有一定的参考价值。
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方法。
以上是关于swift 将图片保存到自定义相册中的主要内容,如果未能解决你的问题,请参考以下文章