swift 2.0 iOS 8.0 album 保存自定义相册

using swift 2.0 save photo to custom album

新建了一个CustomAblum类,写成了单例, 这个写单例的方式是swift中的最好的一种方式:

staticletsharedInstance = CustomAblum()

定义几个变量:

varassetCollection: PHAssetCollection!varalbumFound : Bool =falsevarphotosAsset: PHFetchResult!varcollection: PHAssetCollection!varassetCollectionPlaceholder: PHObjectPlaceholder!staticletalbumName ="爱拍美图"

在初始化方法中创建自定义相册

init() {self.createAlbum()    }

privatefunccreateAlbum(){letfetchOptions =PHFetchOptions()        fetchOptions.predicate =NSPredicate(format:"title = %@",CustomPhotoAlbum.albumName)letcollection :PHFetchResult=PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)iflet_:AnyObject= collection.firstObject {self.albumFound =trueassetCollection = collection.firstObjectas!PHAssetCollection}else{PHPhotoLibrary.sharedPhotoLibrary().performChanges({letcreateAlbumRequest :PHAssetCollectionChangeRequest=PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(CustomPhotoAlbum.albumName)self.assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection                }, completionHandler: { success, errorinself.albumFound = (success ?true:false)if(success) {letcollectionFetchResult =PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([self.assetCollectionPlaceholder.localIdentifier], options:nil)print(collectionFetchResult)self.assetCollection = collectionFetchResult.firstObjectas!PHAssetCollection}            })        }    }

写一个saveImage方法:

funcsaveImage(image: UIImage){ifself.assetCollection !=nil{PHPhotoLibrary.sharedPhotoLibrary().performChanges({letassetChangeRequest =PHAssetChangeRequest.creationRequestForAssetFromImage(image)letassetPlaceholder = assetChangeRequest.placeholderForCreatedAssetletalbumChangeRequest =PHAssetCollectionChangeRequest(forAssetCollection:self.assetCollection)                albumChangeRequest?.addAssets([assetPlaceholder!])                }, completionHandler:nil)        }    }

调用保存时,这样调用:

CustomPhotoAlbum.sharedInstance.saveImage(image)

文/ShawnDu(作者)

原文链接:http://www.jianshu.com/p/365a30d6510f

著作权归作者所有,转载请联系作者获得授权,并标注“作者”。

你可能感兴趣的:(swift 2.0 iOS 8.0 album 保存自定义相册)