我正在尝试将 UIImage
转换为 PHAsset
但找不到任何解决方案。我发现的只是反之亦然(即 PHAsset
到 UIImage
)。
场景是,我从自定义目录中获取图像到 PHAssetCollection
中并显示在 UICollectionView
中。我还想在此处包含来自先前屏幕的更多图像,这些图像来自远程源。我不想将远程图像保存到我的目录中,而是想将它们包含在我的 UICollectionView
中。
请给我建议解决方案或一些好的替代方案,以便 UICollectionView
的来源相同(即 PHAssetCollection
)
最佳答案
聚会有点晚了,但我会为 future 的人发布我的答案。
我在我的应用中所做的是截取屏幕截图并保存到照片应用中的专用相册。
以下示例中的getAlbum()
只是一个检索相册的辅助方法。
ImageStoreItem
只是一个包含两个字段的包装器:image: UIImage
和 id: String
作为原始 PHAsset 的标识符
。
/**
Saves the image to the album in the Photos app.
- Throws:
- `ImageStore.TypeError.accessDenied`
if the user has denied access to the photo library.
- An error thrown by `PHPhotoLibrary`.
*/
func saveImage(_ image: UIImage) throws {
let album = try getAlbum()
try PHPhotoLibrary.shared().performChangesAndWait {
let imgReq = PHAssetChangeRequest.creationRequestForAsset(from: image),
albReq = PHAssetCollectionChangeRequest(for: album)!
albReq.addAssets([imgReq.placeholderForCreatedAsset] as NSFastEnumeration)
}
}
/**
Fetches images in the app album.
- Throws:
- `ImageStore.TypeError.accessDenied`
if the user has denied access to the photo library.
- An error thrown by `PHPhotoLibrary`.
- `NSError` thrown by `PHImageManager`
if fetching images from the `PHAsset` list failed.
- `Globalerror.unknown` if no image was fetched,
but there is no corresponding error object.
- Returns:
An array of `ImageStoreItem`s with the album items.
*/
func getImages() throws -> [ImageStoreItem] {
let album = try ImageStore.shared.getAlbum(),
assets = PHAsset.fetchAssets(in: album, options: nil)
let size = UIScreen.main.bounds.size,
opt = PHImageRequestOptions()
opt.isSynchronous = true
var res = [ImageStoreItem]()
var err: Error? = nil
let handler: (PHAsset) -> (UIImage?, [AnyHashable : Any]?) -> Void =
{ (asset) in
{ (image, info) in
if let image = image {
let item = ImageStoreItem(image: image,
id: asset.localIdentifier)
res.append(item)
} else if let info = info {
if let error = info[PHImageErrorKey] {
err = error as! NSError
} else {
var userInfo = [String : Any]()
for (key, value) in info {
userInfo[String(describing: key)] = value
}
err = GlobalError.unknown(info: userInfo)
}
}
}
}
assets.enumerateObjects { (asset, _, _) in
PHImageManager.default()
.requestImage(for: asset,
targetSize: size,
contentMode: .default,
options: opt,
resultHandler: handler(asset))
}
if let error = err { throw error }
return res
}
documentation on the PhotoKit不是太令人印象深刻,但在这里和那里看一看,您就会掌握它的窍门。
关于ios - UIImage 到 PHAsset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37043933/