ahe*_*eze 5 ios swift photokit phasset
我用来UIImageWriteToSavedPhotosAlbum将图像保存到照片应用程序。这是我发现的唯一可以让您执行此操作的功能。
这是我的代码:
import UIKit
import Photos
class ViewController: UIViewController {
/// photo of a cactus
let photoURL = URL(string: "https://raw.githubusercontent.com/aheze/DeveloperAssets/master/cactus.png")! /// in my app it's actually a local URL, but this also works
func saveToPhotos() {
DispatchQueue.global().async {
let data = try? Data(contentsOf: self.photoURL)
let image = UIImage(data: data!)
UIImageWriteToSavedPhotosAlbum(image!, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
}
/// called when the image saving is complete
@objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
print("Finished saving image")
/// how to get localIdentifier of the image?
let asset = PHAsset() /// obviously this does not work...
let localIdentifier = asset.localIdentifier
}
}
Run Code Online (Sandbox Code Playgroud)
图像已成功保存到照片应用程序。但是,我需要保留对它的引用,最好是它的localIdentifier,这样我将来就可以在用户的其他照片中找到它。
例如,当我fetchAllPhotos稍后打电话时,我需要某种方法来找到我保存的仙人掌照片。
var allPhotos: PHFetchResult<PHAsset>?
func fetchAllPhotos() {
let fetchOptions = PHFetchOptions() /// get all of user's photos
allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
if let photos = allPhotos {
photos.enumerateObjects { (asset, index, stop) in
/// I need to find the image!
/// So I need to know its localIdentifier back when I saved it.
if asset.localIdentifier == "cactus" {
print("photo has been found")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我有什么办法可以做到这一点吗?完成UIImageWriteToSavedPhotosAlbum处理程序引用,所以也许我可以从中UIImage创建一个?PHAsset或者也许我可以向 的UIImage元数据写入一些内容,我不确定。
尝试保存图像逻辑:
try PHPhotoLibrary.shared().performChangesAndWait {
let imgReq = PHAssetChangeRequest.creationRequestForAsset(from: image)
self.localID = imgReq.placeholderForCreatedAsset.localIdentifier
}
Run Code Online (Sandbox Code Playgroud)
您可以通过以下方式获取本地ID:
photos.enumerateObjects { (asset, index, stop) in
if asset.localIdentifier == self.localID {
print("photo was found")
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2985 次 |
| 最近记录: |