iOS save photo in an app specific album

后端 未结 5 2125
天命终不由人
天命终不由人 2020-11-30 01:24

I\'m creating an iOS 5 app. I want to save a photo to the device.

I want to save the photo to an album specific to my app, so I need to create the album, and then sa

5条回答
  •  不知归路
    2020-11-30 02:14

    Adaptation of Eddy's answer for Swift 4:

        func saveImageToAlbum(_ image: UIImage, name: String) {
    
            if let collection = fetchAssetCollection(name) {
                self.saveImageToAssetCollection(image, collection: collection)
            } else {
                // Album does not exist, create it and attempt to save the image
                PHPhotoLibrary.shared().performChanges({
                    PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: name)
                }, completionHandler: { (success: Bool, error: Error?) in
                    guard success == true && error == nil else {
                        NSLog("Could not create the album")
                        if let err = error {
                            NSLog("Error: \(err)")
                        }
                        return
                    }
    
                    if let newCollection = self.fetchAssetCollection(name) {
                        self.saveImageToAssetCollection(image, collection: newCollection)
                    }
                })
            }
        }
    
        func fetchAssetCollection(_ name: String) -> PHAssetCollection? {
    
            let fetchOption = PHFetchOptions()
            fetchOption.predicate = NSPredicate(format: "title == '" + name + "'")
    
            let fetchResult = PHAssetCollection.fetchAssetCollections(
                with: PHAssetCollectionType.album,
                subtype: PHAssetCollectionSubtype.albumRegular,
                options: fetchOption)
    
            return fetchResult.firstObject
        }
    
        func saveImageToAssetCollection(_ image: UIImage, collection: PHAssetCollection) {
    
            PHPhotoLibrary.shared().performChanges({
    
                let creationRequest = PHAssetCreationRequest.creationRequestForAsset(from: image)
                if let request = PHAssetCollectionChangeRequest(for: collection),
                    let placeHolder = creationRequest.placeholderForCreatedAsset {
                    request.addAssets([placeHolder] as NSFastEnumeration)
                }
            }, completionHandler: { (success: Bool, error: Error?) in
                guard success == true && error == nil else {
                    NSLog("Could not save the image")
                    if let err = error {
                        NSLog("Error: " + err.localizedDescription)
                    }
                    return
                }
            })
        }
    

提交回复
热议问题