ios 개발중 사진촬영을 했을때 디폴트 앨범에 저장하지 않고

다른 사진첩을 만들어 그곳에 사진을 저장하고 싶을 때 아래의 코드를 사용해보자.


우선 swift 파일을 하나 생성하여 아래와 같이 코딩한다.(swift3 반영)

import Photos


class CustomPhotoAlbum{


    static let albumName = "MyCloset"

    static let sharedInstance = CustomPhotoAlbum()

    

    var assetCollection: PHAssetCollection!

    

    init() {

        

        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! as PHAssetCollection

            }

            

            return nil

        }

        

        if let assetCollection = fetchAssetCollectionForAlbum() {

            self.assetCollection = assetCollection

            return

        }

        

        PHPhotoLibrary.shared().performChanges({

            PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: CustomPhotoAlbum.albumName)

        }) { success, _ in

            if success {

                self.assetCollection = fetchAssetCollectionForAlbum()

            }

        }

    }

    

    func saveImage(image: UIImage) {

        

        if assetCollection == nil {

            return   // If there was an error upstream, skip the save.

        }

        

        PHPhotoLibrary.shared().performChanges({

            let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)

            let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)

            albumChangeRequest?.addAssets([assetChangeRequest.placeholderForCreatedAsset!] as NSArray)

        }, completionHandler: nil)

    }

    

}



기본앨범에 저장할때 사용했던


IImageWriteToSavedPhotosAlbum(image, self, #selector(AddClothesViewController.image(image:didFinishSavingWithError:contextInfo:)), nil)


위의 코드 대신 아래의 코드를 사용하여 저장한다.


ustomPhotoAlbum.sharedInstance.saveImage(image: image)


swift3 부터 Info.plist 파일에 설정했던 photoLibrary 사용권한을 넣는 것도 잊지 않도록 한다.

+ Recent posts