Document based App hangs with async on iOS

I only changed the ContentView.swift with the following lines.

How to reproduce:

  1. click + to create document after app runs.

  2. click the newly created Untitled document.

  3. stay 2 secs

  4. click < on the top to go back

  5. then repeat 2-3-4

  6. the app becomes unresponsive after about 6 rounds

The whole process takes about 10 secs.
The <, + on the top and the file items all don't have response.

Where am I wrong. Thanks

iOS: 15.0.2
Xcode: 13.0 (13A233)
template: iOS / Document App

import SwiftUI
struct ContentView: View {
    @Binding var document: testDocument
    @State var isauth = false
    var body: some View {
        //TextEditor(text: $document.text)
            if !isauth {
                Text("Not authenticated, verifying...!")
            } else {
                Text("Ready to unlock classified files, cool!")
        }.task { await mytask() }
    func mytask() async {
        //need to check something repeatedly, complicated computation inside...
        while true {
            isauth = !isauth
            print("\(#file):\(#line):", isauth)  //this can print

It sounds like the tasks you detach on each viewing are never cancelled or otherwise ended and eventually consume all of the MainActor. I suggest you properly track your expensive work and cancel it when you navigate back.

Thanks Jon

Now I replace the single sleep(1) inside the while loop with the following lines.
It seems getting better, but the catch block still prints CancellationError.

Is this the right way to do it.


    if Task.isCancelled { break }

    do {
        try await Task.sleep(nanoseconds: 1_000_000_000)
    } catch {
        print("\(#file):\(#line):", error) // still get CancellationError
Terms of Service

Privacy Policy

Cookie Policy