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

设置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)
                    }
                }
        }
        
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容