I have the following test code:
import SwiftUI
struct ContentView: View {
@State private var draggedImages: [UIImage?] = Array(repeating: nil, count: 5)
@State private var savedToDisk = false
var body: some View {
VStack {
HStack {
ForEach(0..<5, id: \.self) { index in
let image = draggedImages[index] ?? UIImage(systemName: "photo")
Image(uiImage: image!)
.resizable()
.frame(width: 80, height: 80)
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
.onDrag {
return NSItemProvider(object: UIImage(systemName: "photo")!)
}
.onDrop(of: ["public.image"], isTargeted: nil) { providers, _ in
providers.first?.loadDataRepresentation(forTypeIdentifier: "public.image") { data, error in
if let data = data, let uiImage = UIImage(data: data) {
draggedImages[index] = uiImage
saveImageToDisk(image: uiImage, imageNumber: index)
}
}
return true
}
}
.alert(isPresented: $savedToDisk) {
Alert(title: Text("Images Saved"), message: Text("The images have been saved to disk."), dismissButton: .default(Text("OK")))
}
Spacer()
}
}
.padding()
}
private func saveImageToDisk(image: UIImage, imageNumber: Int) {
if let imageData = image.pngData() {
do {
let documentsDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let imageUrl = documentsDirectory.appendingPathComponent("image_\(imageNumber).png")
try imageData.write(to: imageUrl)
savedToDisk = true
} catch {
print("Error saving image: \(error)")
}
}
}
}
I can drag and drop as well as the dragged image is save on the second placeholder thru the fifth but not the first When I drag and drop to the first image another files app opens but when I close this the image is not saved. Any Ideas why the first image behaves differently to all the others?
I test on Sonoma and Xcode 15 beta 7, I wil give it a try on Ventura and Xcode 14 later today to see if the same thing happens. Thanks