PHAsset相册中的资源
PHAssetCollection 相册 是PHAsset的一个集合
PHPhotoLibrary 图库代表整个相册
可以执行一些增删等操作
PHImageManager 访问PHAsset里的真正的图片或者视频
PHAssetChangeRequest 是改变类,需要PHPhotoLibrary去执行
PHCachingImageManager 取资源时的缓存设置
func createAlbum() {
//查找又没有创建"我创建的"这个相册,没有的话再创建 ,遍历的是用户自定义的相册不是智能相册
let result = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: nil)
result.enumerateObjects { (collect, index, stop) in
if collect.localizedTitle == "我创建的" {
stop.pointee = true
}
if index == result.count-1 {
PHPhotoLibrary.shared().performChanges {
PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: "我创建的")
} completionHandler: { (flag, error) in
print(error)
}
}
}
}
func addPhoto() {
let result = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: nil)
result.enumerateObjects { (collect, index, stop) in
if collect.localizedTitle == "我创建的" {
stop.pointee = true
PHPhotoLibrary.shared().performChanges {
let image = UIImage(named: "home_banner")
PHAssetChangeRequest.creationRequestForAsset(from: image!)
let request = PHAssetCollectionChangeRequest(for: collect)
let placeholder = request?.placeholderForCreatedAssetCollection
request?.addAssets([placeholder] as NSFastEnumeration)
} completionHandler: { (flag, error) in
print(error)
}
}
}
}
func deletePhoto() {
let result = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: nil)
result.enumerateObjects { (collect, index, stop) in
if collect.localizedTitle == "我创建的" {
stop.pointee = true
let result = PHAsset.fetchAssets(in: collect, options: nil)
result.enumerateObjects { (asset, index, stop) in
PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .aspectFill, options: nil) { (image, dict) in
}
PHPhotoLibrary.shared().performChanges {
if index == collect.accessibilityElementCount()-1 {
stop.pointee = true
PHAssetCollectionChangeRequest.deleteAssetCollections([asset] as NSFastEnumeration)
}
} completionHandler: { (flag, error) in
print(error)
}
}
}
}
}
网友评论