0

The code from https://github.com/onmyway133/blog/issues/594, and make some changes.

It's very simple, create a SwiftUI + Appkit project, copy and paste the code below to the project.

import SwiftUI

struct SelectFileView: View {
  let buttonTitle: String
  @State var isDrop: Bool = false
  
  var body: some View {
    VStack(alignment: .leading) {
      Button(action: {}) {
        Text(buttonTitle)
      }
      .offset(x: -16)
      Text("Alternatively, you can drag and drop file here")
        .font(.footnote)
        .foregroundColor(Color.gray)
    }
    .border(isDrop ? Color.orange : Color.clear)
    .onDrop(of: ["public.image"], delegate: self)
    .padding(32)
  }
}

extension SelectFileView: DropDelegate {
  func dropEntered(info: DropInfo) {
    print("dropEntered")
    self.isDrop = true
  }
  
  func dropExited(info: DropInfo) {
    print("dropExited")
    self.isDrop = false
  }
  
  func performDrop(info: DropInfo) -> Bool {
    guard
      let itemProvider = info.itemProviders(for: ["public.image"]).first
    else { return false }
    
    itemProvider.loadItem(forTypeIdentifier: "public.image", options: nil) { item, error in
      guard
        let data = item as? Data,
        let url = URL(dataRepresentation: data, relativeTo: nil)
      else { return }
      
    }
    
    return true
  }
}

struct ContentView: View {
  var body: some View {
    SelectFileView(buttonTitle: "Drop Test")
  }
}

After building and running on Xcode 12.0 beta 2 (12A6163b), it always print dropExited, and this is the problem.

dropEntered(info:) not trigged, but dropExited(info:) works

Donly
  • 55
  • 8
  • 1
    How do you test it? If you try to drop image file from Finder then there is no "public.image" image provider in it. Try "public.file-url", also [this answer](https://stackoverflow.com/a/60832686/12299030) can be helpful. – Asperi Jul 09 '20 at 05:11
  • Very thanks to @Asperi, as in Catalyst app the code above is works. For AppKit must use `public.file-url` for Type Identifier. – Donly Jul 09 '20 at 06:30
  • This question has been asked in many places (e.g. https://stackoverflow.com/questions/71041158/swiftui-cannot-make-performdrop-work-with-uttype) but nobody seems to have an answer. I'm convinced this is a bug with `.onDrop()` not working with UTTypes other than `UTType.fileURL` – trinth Feb 04 '23 at 06:30

0 Answers0