SwiftUI: Drag images from browser to macOS app (tutorial with source code)

I've spent quite a bit of time researching how to programmatically drag images from a web browser into a macOS application. Unfortunately, there are very few resources available on this topic.

However, after some in-depth research, coding, and debugging, I finally made it work!

1_tTcUqagAblL0S6QjfCR4SQ.gif

prerequisites

MacBook
Xcode
Browser
You also need a basic understanding of SwiftUI.

Setup items

Open Xcode: If you don't have Xcode installed yet, install it.
Create a new project: Select App under macOS, then select the App template.
Configure project: Enter name, organization and identifier. Select Swift as the language. For this example, you can skip core data, unit tests, and UI tests.
Choose a location to save your project.

user interface

The user interface (UI) of this project is very simple: a window where the user can place images. Once you drag the image into the window, the image appears.

struct ContentView: View {
  @State private var image: NSImage?
  
  var body: some View {
    VStack {
      if let image = image {
        Image(nsImage: image)
          .resizable()
          .aspectRatio(contentMode: .fit)
          .frame(maxWidth: .infinity, max

Guess you like

Origin blog.csdn.net/iCloudEnd/article/details/133410368