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

标签 ios swift

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

最佳答案

使用此类并在需要时和将图像添加到相册之前请求许可。

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."
                        })
                    })

关于ios - 如何在 Swift 3 iOS 10 中创建自定义相册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44666929/

相关文章:

ios - 解析不会编译

ios - 具有相同键的 NSDictionary 对象

ios - 在ContainerView中打开不同的 View

ios - 强制标签文本从左到右,同时包括一些从右到左的文本

ios - Swift 正确使用 getter 和 setter

ios - HTTP POST 请求后 UIView 更改延迟

swift - 如何创建一个包含多个表格单元格的普通表格,每个表格单元格都链接到自己的推送转场?

iphone - UITableViewController 和 subview

iphone - iOS:企业服务器架构

ios - 由于错误 :,JSON 无法序列化