skip to Main Content

OK, all of a sudden I’m getting warnings (and runtime errors) in code that hasn’t changed in quite some time. I believe this has to do with Swift concurrency.

Further details below. All help appreciated greatly. On where to look next.

Using the example code from Apple also shows this issue.
enter image description here

I’m getting errors using the new environment variables to open an existing document: Apple Developer Link

I get this error when I have my swiftui View as being @MainActor:
enter image description here

I get this error without it:
enter image description here

I get this if I set the Task to run on the Main Actor
enter image description here

Run time crash:
enter image description here

And console output on runtime crash:
enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    Thank you @Lorem Ipsum and @malhal for trying to help and not just down voting.

    For others having similar issues the answer was to do as Lorem ipsum suggested to make the parent view @MainActor, but also to pull the code out of the view body and into it's own method and call that async method from a Task call within the view body.

    In my code I am declaring the Environment variable within the view as before but have moved the call to it to a function inside the View:

    @MainActor struct ExistingProjectButton: View {
        @Environment(.openDocument) private var openDocument
    
    var body: some View {
    ...
    .simultaneousGesture(TapGesture(count: 2).onEnded {
        Task{
            await openExistingDocument(url: buttonURL)
        }
    }
    
    
    func openExistingDocument(url: URL) async{
            do {
                try await openDocument(at: url)
            } catch {
                // Handle error
                print("Error opening: (error.localizedDescription)")
            }
        }
    }
    

  2. It’s .task in SwiftUI not Task. In your case probably something like:

    .onGesture {
        count += 1
    }
    .task(id: count) {
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search