如何在Swift 3 iOS 10中创建自定义相册

时间:2017-06-21 04:32:20

标签: ios swift

这可能听起来很重复,但在搜索之后我还没有得到Swift 3的预期答案。 在我尝试使用addAssets()方法添加资产时,为资产创建占位符后Xcode建议我将assetPlacehoder强制转换为FastEnumeration类型。当我这样做时,它会导致异常。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:2)

使用此课程并在需要时以及在将图像添加到相册之前请求获得许可。

class CustomPhotoAlbum: NSObject {

        static let albumName = "YourAlbumName"
        static let sharedInstance = CustomPhotoAlbum()

        var assetCollection: PHAssetCollection!

        override init() {
            super.init()

            if let assetCollection = fetchAssetCollectionForAlbum() {
                self.assetCollection = assetCollection
                return
            }
        }

        func requestAuthorizationHandler(status: PHAuthorizationStatus) {
            if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
                // ideally this ensures the creation of the photo album even if authorization wasn't prompted till after init was done
                print("trying again to create the album")
                self.createAlbum()
            } else {
                print("should really prompt the user to let them know it's failed")
            }
        }

        func createAlbum() {
            PHPhotoLibrary.shared().performChanges({
                PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: CustomPhotoAlbum.albumName)   // create an asset collection with the album name
            }) { success, error in
                if success {
                    self.assetCollection = self.fetchAssetCollectionForAlbum()
                } else {
                    print("error \(String(describing: error))")
                }
            }
        }

        func fetchAssetCollectionForAlbum() -> PHAssetCollection? {
            let fetchOptions = PHFetchOptions()
            fetchOptions.predicate = NSPredicate(format: "title = %@", CustomPhotoAlbum.albumName)
            let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)

            if let _: AnyObject = collection.firstObject {
                return collection.firstObject
            }
            return nil
        }

    func save(image: UIImage , completion : @escaping () -> ()) {
            if assetCollection == nil {
                return                          // if there was an error upstream, skip the save
            }

            PHPhotoLibrary.shared().performChanges({
                let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
                let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset
                let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)
                let enumeration: NSArray = [assetPlaceHolder!]

                if self.assetCollection.estimatedAssetCount == 0
                {
                    albumChangeRequest!.addAssets(enumeration)
                }
                else {
                    albumChangeRequest!.insertAssets(enumeration, at: [0])
                }

            }, completionHandler: { status , errror in
                completion( )  
            })
        }
}

将此方法称为要保存图像的位置。

CustomPhotoAlbum.sharedInstance.save(image: YourImage, completion: {

                        DispatchQueue.main.async(execute: {
                            //"Any UI update should be in main thread."
                        })
                    })