Home > database >  Add Running Apps to Picker in macOS
Add Running Apps to Picker in macOS

Time:12-13

I want to fetch all running apps on macOS and add them to a Picker view, but I can't work out how to do it.

Picker(selection: $stopAppTerminate.onChange(StopAppTerminateChange), label: Text("Wait for App Termination ")) {
                var workspace = NSWorkspace.shared
                var applications = workspace.runningApplications
                var i: Int = 0

                ForEach(applications) { application in //, id: \.localizedName) { application in
                    Text(String(application)).tag(i   1)
                }
            }

But the ForEach loop fails to compile with "No exact matches in call to initializer".

CodePudding user response:

The Picker needs a binding of the right type and in the picker options tags of the same type.

As workspace.runningApplications is of Type NSRunningApplication you can define an optional State var of the same type. Then inside the picker you iterate through the applications with ForEach and the associated app value in .tag().

    @State private var selectedApp: NSRunningApplication?
    
    var body: some View {
        var workspace = NSWorkspace.shared
        var applications = workspace.runningApplications
        
        Picker("App", selection: $selectedApp) {
            Text("No selection").tag(nil as NSRunningApplication?)
            ForEach(applications, id: \.bundleIdentifier) { app in
                HStack {
                    if let icon = app.icon {
                        Image(nsImage: icon)
                    }
                    Text(app.localizedName ?? "?")
                }
                .tag(app as NSRunningApplication?)
            }
        }
    }
  • Related