Search code examples
swiftswiftuiphotokit

delete photo after selection


So, I have a SwiftUI app that lets the user parses content for a selected image and saves it for later use. The part is done. I want to remove the chosen picture from the user's photo library once the parsing is done.

Here's a simplified version of my code:

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")")
            }
        }
    }
}

Any idea how to get the asset identifier? Or any other workaround that would help achieve my goal is very welcome


Solution

  • The reason, I think that you got nil identifiers is because you haven't specified a photo library when you created the PhotosPicker.

    For example:

    PhotosPicker(selection: $photosPickerItem, matching: ..., photoLibrary: .shared()))