1.判断相册访问权限

let status = PHPhotoLibrary.authorizationStatus()
        
if status == .restricted || status == .denied {
            print("无法访问相册")
}

2.实时监听相册内部图片变化
遵守PHPhotoLibraryChangeObserver协议

PHPhotoLibrary.shared().register(self)


func photoLibraryDidChange(_ changeInstance: PHChange) {
     print("相册变化的运行代码")
}

3.读取相册内所有图片资源

func getAllAssetInPhoto(_ ascending: Bool) -> [PHAsset] {
        var phs : [PHAsset] = []
        let option = PHFetchOptions()
        option.sortDescriptors = [NSSortDescriptor(key: "creationDate",
                                                   ascending: ascending)]
        let result = PHAsset.fetchAssets(with: .image, options: option)

        result.enumerateObjects { (obj, idx, stop) in
            let asset : PHAsset = obj
            phs.append(asset)
        }

        return phs
    }

4.根据获取的PHAsset对象,解析图片

func getAllAssetInPhoto(_ ascending: Bool) -> [PHAsset] {
        var phs : [PHAsset] = []
        let option = PHFetchOptions()
        option.sortDescriptors = [NSSortDescriptor(key: "creationDate",
                                                   ascending: ascending)]
        let result = PHAsset.fetchAssets(with: .image, options: option)

        result.enumerateObjects { (obj, idx, stop) in
            let asset : PHAsset = obj
            phs.append(asset)
            let option : PHImageRequestOptions = PHImageRequestOptions()
            option.resizeMode = .fast
            option.isNetworkAccessAllowed = true
            PHCachingImageManager.default().requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: option, resultHandler: { (img, info) in
                print("img就是拿到的图片")
//              PHImageManagerMaximumSize这个代表全尺寸,当然你可以传入你想要的尺寸
            })
        }

        return phs
 }

5.获取所有智能相册

let smartAlbum = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil)
smartAlbum.enumerateObjects { (collecion, idx, stop) in
    print("相册名字\(collecion.localizedTitle)")
}

目前拿到的相册名字是英文的
可以到info这边添加CFBundleAllowMixedLocalizations这个key,并设置为True
这样能获取到中文的相册标题。

6.删除相册里面的图片

let assets = getAllAssetInPhoto(true)

PHPhotoLibrary.shared().performChanges({
    let result = PHAsset.fetchAssets(withLocalIdentifiers: [assets[0].localIdentifier], options: nil)
    PHAssetChangeRequest.deleteAssets(result)
}) { (finish, error) in

}