rodrigoalves rodrigoalves - 1 year ago 90
iOS Question

How to save image to custom album?

I have a brand new iOS app that generates images and lets the users save them into the Camera SavedPhotosAlbum. However, I wanna do something like Snapchat and Frontback, and save these images also to a custom-named album.

So this is my code right now:

let imageToSave = self.currentPreviewImage

let softwareContext = CIContext(options:[kCIContextUseSoftwareRenderer: true])
let cgimg = softwareContext.createCGImage(imageToSave, fromRect:imageToSave.extent())

ALAssetsLibrary().writeImageToSavedPhotosAlbum(cgimg,, completionBlock:nil)

I've seen a few examples of people doing this in Objective-C but nothing that I could translate to Swift, and I've check the
method signatures and none of them seem to allow saving to a custom album.

Answer Source

I came up with this singleton class to handle it:

import Photos

class CustomPhotoAlbum {

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

    var assetCollection: PHAssetCollection!

    init() {

        func fetchAssetCollectionForAlbum() -> PHAssetCollection! {

            let fetchOptions = PHFetchOptions()
            fetchOptions.predicate = NSPredicate(format: "title = %@", CustomPhotoAlbum.albumName)
            let collection = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)

            if let firstObject: AnyObject = collection.firstObject {
                return collection.firstObject as! PHAssetCollection

            return nil

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

        }) { success, _ in
            if success {
                self.assetCollection = fetchAssetCollectionForAlbum()

    func saveImage(image: UIImage) {

        if assetCollection == nil {
            return   // If there was an error upstream, skip the save.

            let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
            let assetPlaceholder = assetChangeRequest.placeholderForCreatedAsset
            let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection)
        }, completionHandler: nil)


When you first instantiate the class, the custom album will be created if it doesn't already exist. You can save an image like this:


NOTE: The CustomPhotoAlbum class assumes the app already has permission to access the Photo Library. Dealing with the permissions is a bit outside the scope of this question/answer. So make sure PHPhotoLibrary.authorizationStatus() == .Authorize before you use it. And request authorization if necessary.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download