swift mac swift app fails to show image view crashes on first run

I have an app that displays photos from a directory that the user chooses (including children directories). 

On launch it checks UserDefaults for stored values, if none from previous run, then asks user to open a directory of photos. Then initializes itself and saves the UserDefaults and also a persistent url so that on subsequent run can re-open directory without user intervention.  

When first run and asks for directory, runs fine in setting up app state and saving UserDefaults and persistent url, but when gets to contentView the ImageView fails to show anything, but app continues running for about 15 or 20 sec. changing photo via timer, but no image displayed and then the crash @main hread 1: EXC_BREAKPOINT (code=1, subcode=0x1b8072158) and occurs seemingly async from the running code. Crash report attached.

Then if re-launch app, it gets the saved UserDefaults, does set up and the runs fine, displaying images! Can even change directories (in the full app, with window commands which are not in this short version of the app.

Are the sandbox entitlements under capabilities enabled and any permission request implemented?

Yep, sandbox entitlements for user selected file and picture folder. There isn't choice of user selected directory.

That is a very interesting crash. It seems that AppKit has compatibility logic related to its use of secure coding, and somehow your app is triggering that.

This is a SwiftUI app, right?

You wrote:

On launch it checks UserDefaults for stored values

Are you using UserDefaults directly? Or via the AppStorage or SceneStorage property wrappers?

Also, how is this ‘on launch’ check done. Do you have a main.swift? Or are you using @main?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Yes, using UserDefaults directly and after the saving of persistent url. Yes have @main. Here is the PictureWindowApp.swift: import SwiftUI

@main

struct PictureWindowApp: App {

    @ObservedObject var appState = AppState()          var body: some Scene {

        WindowGroup {

            ContentView(appState: appState)                 .edgesIgnoringSafeArea(.all)                 .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification), perform: { _ in                     NSApp.mainWindow?.standardWindowButton(.zoomButton)?.isHidden = true                     NSApp.mainWindow?.standardWindowButton(.closeButton)?.isHidden = true                     NSApp.mainWindow?.standardWindowButton(.miniaturizeButton)?.isHidden = true                 })         }         .windowStyle(.hiddenTitleBar)         .windowToolbarStyle(UnifiedCompactWindowToolbarStyle())         .commands {             PictureWindowCommands(appState: appState)         }

    }

}

    

Will attach top portion of that file, declarations and init here.

Not sure how to post to preserve format.

Use a code block for that. See Quinn’s Top Ten DevForums Tips for this and other suggestions.

As to your main issue, I don’t have any good suggestions. As I mentioned above, something about the way that your app is structured is triggering a trap in AppKit’s state restoration logic, where it expects secure coding to be used consistently. Untangling that is going to require a deep investigation, which is more than I have time for here on DevForums.

I recommend that you start ripping stuff out of your app (on a branch, obviously :-) to come up with the smallest possible app that reproduces the problem. That yields two benefits:

  • The process of removing stuff might yield interesting clues as to what’s triggering it.

  • If you get to the end and you still don’t understand the issue, you have a minimal test project that you can share with others. And by that I mean you could potentially file a bug about this, or open a DTS tech support incident, or both.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

The other symptom is that despite all the prep that is successful, the Image() in contentView fails to open a window and show the image that was opened/loaded. I am in process of stripping app, have a test version that is somewhat smaller called ImageTest with same symptoms.

I have submitted a stripped down version, ImageTest(101) thru Feedback Assistant, along with a copy of the app and crash report.

Have narrowed down problem. When first run, there is no image, and have user open a local file. I then create and save the bookmark for that, so on subsequent run, can access files based on user having already done so. If I call the function to save bookmark, it saves successfully, but when gets to image view, fails to display the image but program continues to run as if all is well. And on next run it retrieves bookmark and opens file and all works fine.

IF I DON'T save bookmark, the program goes on to work and displays image all is well. But on next run of course, fails since there is no bookmark saved. Here is function that saves bookmark: func saveBookmarkForSelectedURL(fileURL: URL?) -> Bool {

        print("enter saveBookmarkForSelectedURL (String(describing: fileURL))")

        do {

            if let selectedURL =  fileURL {

                // Create a security-scoped bookmark

                // "Returns bookmark data for the URL, created with specified options and resource values."

                // Return Value: Type: Data - A bookmark for the URL.

                let bookmarkData = try selectedURL.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)

                // get an instance of UserDefaults

                let userDefaults = UserDefaults.standard

                //  store the newly-created bookmark in UserDefaults

                // accessible with a meaningful key; user defaults supports storing

                // and fetching the Data/NSData types

                userDefaults.set(bookmarkData, forKey: "PermanentFileBookmark")

                // creating the bookmark did not throw an error, so return positive

                print("just stored bookmark (bookmarkData)")

                return true

            } else {

                print("ERROR: You cannot bookmark a URL that is nil")

                return false

            }

        } catch let error {

            print("Could not create a bookmark because: ", error)

            return false  }

    } // end func saveBookmarkForSelectedURL()

Hi,

I have a similar problem. App crashes with the same error as in OP, and window with selected image does not show (In my case I load a SCNScene from a user-selected .usdz file.)

Is there a resolution?

thx

This is a minimal app that crashes after selecting a .usdz file.

Error: Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1a7f15ba4) "Secure coding for state restoration requested after it was initialized without. NSApplicationDelegate was probably established too late."

import SwiftUI
import SceneKit

func sceneFromFile() -> SCNScene? {
  var scene: SCNScene?
  let panel = NSOpenPanel()
  panel.allowsMultipleSelection = false
  panel.canChooseDirectories = false
  if panel.runModal() == .OK {
    if let sceneURL = panel.url {
      scene = try? SCNScene(url: sceneURL)
    }
  }
  return scene
}


@main
struct SceneFromFileCrashApp: App {
  let scene = sceneFromFile()
  var body: some Scene {
    WindowGroup {
      SceneView(scene: scene)
    }
  }
}

crash report attached

The crash disappears when the App Sandbox entitlement is set to NO.

But then a new log entry appears:

flock failed to lock list file (/var/folders/bg/t20_gl712tj3g9tx5yn730740000gn/C//Magenta.KanaConsole.SceneFromFileCrash/com.apple.metal/16777235_530/functions.list): errno = 35

Solved by removing the let scene = sceneFromFile() initializer.

Instead I added a button to explicitly load the file after an initial layout was done. I don't know how to do it without the button since an .onAppear { scene = sceneFromFile() } or .task { scene = sceneFromFile() } respectively crash or don't do anything.

Still feels like a bug.

import SceneKit

func sceneFromFile() -> SCNScene? {
  var scene: SCNScene?
  let panel = NSOpenPanel()
  panel.allowsMultipleSelection = false
  panel.canChooseDirectories = false
  if panel.runModal() == .OK {
    if let sceneURL = panel.url {
        scene = try? SCNScene(url: sceneURL)
    }
  }
  return scene
}

@main
struct SceneFromFileCrashApp: App {
  @State var scene: SCNScene?
   
  var body: some Scene {
    WindowGroup {
      VStack {
        Button("Open") {
          scene = sceneFromFile()
        }
        SceneView(scene: scene)
      }
    }
  }
}
swift mac swift app fails to show image view crashes on first run
 
 
Q