SwiftUI NSOpenPanel runs but then crashes Mac app

I have a SwiftUI Mac app I am writing... it starts out by calling a func (fileOpenDialog) that calls NSOpenPanel.runModal()...

The NSOpenPanel shows and lets me choose a file... but then crashes the app on Open.

If I don't use NSOpenPanel and just hardcode a file path, everything works fine.

import SwiftUI



struct DialogsTestView: View {

	

	var csvURLString = fileOpenDialog()[0]?.path

//	var csvURLString = "/Users/tj4shee/track.csv"
func fileOpenDialog() -> [URL?]

{

	

	let openPanel = NSOpenPanel()

	

	openPanel.title = "Choose csv file"

	openPanel.message = "Choose the csv file you want to convert to JSON"

	openPanel.showsResizeIndicator = false

	openPanel.allowedContentTypes = [UTType.delimitedText]

	openPanel.showsHiddenFiles = false

	openPanel.canChooseFiles = true

	openPanel.canChooseDirectories = false

	openPanel.allowsMultipleSelection = false

	

	let results = openPanel.runModal()

	return results == .OK ? openPanel.urls : []

}

Thanks for any help, TJ

A little more info... it seems to occur when trying to draw my view ???

This code successfully runs... prints "before", the contents of my file and "after"... then crashes before I see any view

			TextEditor(text: $csvText)

				.onAppear {

					do {

						print("before")

						csvText = try String(contentsOf: csvURL)

						print(csvText)

						print("after")

					} catch {

						print("Failure with \(csvURL.path)\nError: \(error)")

					}

				}

but like I said, if I define csvURL by hardcoding a path in csvURLString... everything works fine

The fileOpenDialog function returns an array of optional URLs. What does that function return when you call it? The following line is going to crash if the array is empty:

var csvURLString = fileOpenDialog()[0]?.path

SwiftUI has a fileImporter modifier that shows an Open panel so you can avoid using NSOpenPanel. Searching for swiftui fileimporter in a search engine brings up several articles on using the file importer. If you still want to use NSOpenPanel with SwiftUI, the following article may help you:

https://serialcoder.dev/text-tutorials/macos-tutorials/save-and-open-panels-in-swiftui-based-macos-apps/

SwiftUI NSOpenPanel runs but then crashes Mac app
 
 
Q