Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom album in Swift 3 iOS 10

Tags:

ios

swift

This may sound repetitive but after searching for while I still not got the intended answer for Swift 3. After creating a placeholder for asset when i'm trying to add Assets using addAssets() method Xcode suggesting me to Cast assetPlacehoder to FastEnumeration type. And when I did so it is causing an exception. Can anybody help me out?

like image 835
Tushar Korde Avatar asked Jun 21 '17 04:06

Tushar Korde


1 Answers

Use this class and ask for permission when you need and before adding image to album.

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( )  
            })
        }
}

Call this method where you want to save image.

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

                        DispatchQueue.main.async(execute: {
                            //"Any UI update should be in main thread."
                        })
                    })
like image 181
Chanchal Warde Avatar answered Oct 17 '22 09:10

Chanchal Warde