iOS 创建自定义相册及保存图片

669 阅读1分钟
设置LocalIdentifier
   private func getLocalIdentifier() -> String{
        return UserDefaults.standard.string(forKey: "AlbumLocalIdentidier") ?? "";
    }
    
    private func setLocalIdentifier(identifier : String){
        print(identifier)
        UserDefaults.standard.set(identifier, forKey: "AlbumLocalIdentidier");
        UserDefaults.standard.synchronize()
    }
通过LocalIdentifier创建自定义相册
//创建自定相册
    func getAlbumCollection() -> PHAssetCollection?{
        var localIdentifier : String! = self.getLocalIdentifier()
        var documentCollection : PHAssetCollection!;
        if localIdentifier!.count == 0{
            PHPhotoLibrary.shared().performChanges({
                localIdentifier = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: CollectionTitle).placeholderForCreatedAssetCollection.localIdentifier;
                self.setLocalIdentifier(identifier: localIdentifier)
            }) { (isHandle, error) in
                if isHandle{
                    print("创建成功")
                }else{
                    print(error)
                }
            }
        }
        
        let assetCollections = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [localIdentifier], options: nil);
        documentCollection = assetCollections.firstObject;
        return documentCollection
    }

#####添加image到自定义相册

   //添加图片到自定义相册
    func saveCollectionToAlbum(assetArr : [PHAsset]){
        let localIdentifier : String! = self.getLocalIdentifier()
        if localIdentifier!.count > 0{
            PHPhotoLibrary.shared().performChanges({
                let albumCollections = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [localIdentifier], options: nil);
                let albumCollection = albumCollections.firstObject;
                let request = PHAssetCollectionChangeRequest(for: albumCollection!)
                request?.addAssets(assetArr as NSFastEnumeration)
                
                }) { (isHandle, error) in
                    if isHandle{
                        print("添加成功")
                    }else{
                        print(error)
                    }
                }
        }
        
    }