所以,我有一个SwiftUI应用程序,它允许用户解析所选图像的内容并保存它以供以后使用。这部分完成了。我想在解析完成后从用户的照片库中删除所选的图片。
下面是我的代码的简化版本:
struct NewItemView: View {
@State private var shouldDeleteImage = true
@State private var photosPickerItem: PhotosPickerItem?
var body: some View {
NavigationView {
Form {
Section("image") {
PhotosPicker(selection: $photosPickerItem) {
Label("Select a Duolingo Photo", systemImage: "photo")
}
}
.onChange(of: photosPickerItem) { selectedPhotosPickerItem in
guard let selectedPhotosPickerItem else {
return
}
debugPrint(selectedPhotosPickerItem)
Task {
isBeingParsed = true
await updatePhotosPickerItem(with: selectedPhotosPickerItem)
isBeingParsed = false
}
}
Section("Parsed content") {
// show content here..
}
}
.navigationTitle("New item")
}
}
private func updatePhotosPickerItem(with item: PhotosPickerItem) async {
photosPickerItem = item
if let photoData = try? await item.loadTransferable(type: Data.self) {
let image = UIImage(data: photoData)
// process the image..
// 💥 it breaks here: itemIdentifier is always nil
self.deleteImage(assetIdentifier: item.itemIdentifier!)
}
}
// how to get the assetIdentifier here 😫
private func deleteImage(assetIdentifier: String) {
let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [assetIdentifier], options: nil)
guard let asset = fetchResult.firstObject else { return }
PHPhotoLibrary.shared().performChanges {
PHAssetChangeRequest.deleteAssets([asset] as NSArray)
} completionHandler: { success, error in
if success {
print("Image deleted from photo library")
} else {
print("Error deleting image from photo library: (error?.localizedDescription ?? "unknown error")")
}
}
}
}
知道如何获得资产标识符吗?或者任何其他有助于实现我的目标的变通方法都是非常受欢迎的
我认为您获得nil
标识符的原因是因为您在创建PhotosPicker
时没有指定照片库。
例如:
PhotosPicker(selection: $photosPickerItem, matching: ..., photoLibrary: .shared()))