My App crashes run-time occasionally when I use AVFoundation and related code

I am developing an app for Vehicle owners with a built-in map navigation feature with voice navigation support. The app works fine without voice navigation but when I use voice navigation it occasionally crashes and it crashes while voice navigation is not in progress.

What makes it impossible to diagnose is that even though it crashed 10 times on the flight, I don't see any crash reports in 'Apple Connect'. I tried running it in a simulator and it didn't crash there! but on a real device, when I drive with the app navigating me I crashes abruptly after a few minutes and it's not while the voice navigation is speaking! I also ran the app without AVFoundation and it did not crash then. So I am 100% sure it is something with this AVFoundation framework.

If anyone can help find the problem in my following code it would be really helpful.

import SwiftUI
import AVFoundation

struct DirectionHeaderView: View {
    @Environment(\.colorScheme) var bgMode: ColorScheme
    var directionSign: String?
    var nextStepDistance: String
    var instruction: String 
    @Binding var showDirectionsList: Bool
    @Binding var height: CGFloat
    @StateObject var locationDataManager: LocationDataManager
    @State private var synthesizer = AVSpeechSynthesizer()
    @State private var audioSession = AVAudioSession.sharedInstance()
    @State private var lastInstruction: String = ""
    @State private var utteranceDistance: String = ""
    @State private var isStepExited = false
    @State private var range = 20.0
    var body: some View {
        VStack {        
            HStack {              
                VStack {                 
                    if let directionSign = directionSign {
                        Image(systemName: directionSign)             
                    }                
                    if !instruction.contains("Re-calculating the route...") {
                        Text("\(nextStepDistance)")
                            .onChange(of: nextStepDistance) {
                                let distance = getDistanceInNumber(distance: nextStepDistance)
                                if distance <= range && !isStepExited {
                                    startVoiceNavigation(with: instruction)
                                    isStepExited = true
                                }                                
                            }
                    }                    
                }             
                Spacer()
                    Text(instruction)
                    .onAppear {
                        isStepExited = false
                        utteranceDistance = nextStepDistance
                         range = nextStepRange(distance: utteranceDistance)
                        startVoiceNavigation(with: "In \(utteranceDistance), \(instruction)")
                    }
                    .onChange(of: instruction) {
                        isStepExited = false
                        utteranceDistance = nextStepDistance
                        range = nextStepRange(distance: utteranceDistance)
                        startVoiceNavigation(with: "In \(utteranceDistance), \(instruction)")
                    }
                        .padding(10)
                Spacer()
            }
        }
        .padding(.horizontal,10)
        .background(bgMode == .dark ? Color.black.gradient : Color.white.gradient)
    }

    func startVoiceNavigation(with utterance: String) {
        if instruction.isEmpty || utterance.isEmpty {
            return
        }
        if instruction.contains("Re-calculating the route...") {
            synthesizer.stopSpeaking(at: AVSpeechBoundary.immediate)
            return
        }
        let thisUttarance = AVSpeechUtterance(string: utterance)
        lastInstruction = instruction
        if audioSession.category == .playback && audioSession.categoryOptions == .mixWithOthers {
            DispatchQueue.main.async {
                synthesizer.speak(thisUttarance)
            }
        }
        else {        
            setupAudioSession()          
            DispatchQueue.main.async {
                synthesizer.speak(thisUttarance)
            }          
        }
    }
    func setupAudioSession() {
        do {
            try audioSession.setCategory(AVAudioSession.Category.playback, options: AVAudioSession.CategoryOptions.mixWithOthers)
            try audioSession.setActive(true)
        }
        catch {
            print("error:\(error.localizedDescription)")
        }
    }
    
    func nextStepRange(distance: String) -> Double {
        var thisStepDistance = getDistanceInNumber(distance: distance)
        if thisStepDistance != 0 {
            switch thisStepDistance {
            case 0...200:
                if locationDataManager.speed >= 90 {
                    return thisStepDistance/1.5
                }
                else {
                    return thisStepDistance/2
                }
            case 201...300:
                if locationDataManager.speed >= 90 {
                    return 120
                }
                else {
                    return 100
                }
            case 301...500:
                if locationDataManager.speed >= 90 {
                    return 150
                }
                else {
                    return 125
                }
            case 501...1000:
                if locationDataManager.speed >= 90 {
                    return 250
                }
                else {
                    return 200
                }
            case 1001...10000:
                if locationDataManager.speed >= 90 {
                    return 250
                }
                else {
                    return 200
                }
            default:
                if locationDataManager.speed >= 90 {
                    return 250
                }
                else {
                    return  200
                } 
            }
        }
        return 200
    }

    func getDistanceInNumber(distance: String) -> Double {
        var thisStepDistance = 0.0
        if distance.contains("km") {
            let stepDistanceSplits = distance.split(separator: " ")
            let stepDistanceText = String(stepDistanceSplits[0])
            if let dist = Double(stepDistanceText) {
                thisStepDistance = dist * 1000
            }
        }
        else {
            var stepDistanceSplits = distance.split(separator: " ")
            var stepDistanceText = String(stepDistanceSplits[0])
            if let dist = Double(stepDistanceText) {
                thisStepDistance = dist               
            }
        }      
        return thisStepDistance
    }
}

#Preview {
    DirectionHeaderView(directionSign: "", nextStepDistance: "", instruction: "", showDirectionsList: .constant(false), height: .constant(0), locationDataManager: LocationDataManager())
}

Hello @sajpanchal,

It sounds like you are able to reproduce this crash on your device, for instructions on how you can get the crash logs, see Locate crash reports and memory logs on the device.

Best regards,

Greg

{"roots_installed":0,"app_name":"Map","timestamp":"2024-11-10 18:11:27.00 -0500","app_version":"1.3.12","slice_uuid":"3130A94E-B368-379D-841C-570727731701","build_version":"1","bundleID":"com.SajPanchal.MyMap","duration_ms":"52417","share_with_app_devs":1,"is_first_party":0,"bug_type":"202","os_version":"iPhone OS 18.1 (22B83)","distributor_id":"com.apple.TestFlight","name":"Map","incident_id":"B1F14177-6041-48F7-AB24-A7AAD84CBA79"}
Date/Time:        2024-11-10 18:10:28.054 -0500
End time:         2024-11-10 18:11:20.472 -0500
OS Version:       iPhone OS 18.1 (Build 22B83)
Architecture:     arm64e
Report Version:   53
Incident Identifier: B1F14177-6041-48F7-AB24-A7AAD84CBA79
Share With Devs:  Yes

Data Source:      Microstackshots
Shared Cache:     743E2861-81DD-307C-99A2-DB5D00B99042 slid base address 0x18640c000, slide 0x640c000

Command:          Map
Path:             /private/var/containers/Bundle/Application/11799D10-D568-4AEE-9E34-F31A657B3034/Map.app/Map
Identifier:       com.SajPanchal.MyMap
Version:          1.3.12 (1)
Is First Party:   No
Beta Identifier:  BD3249ED-F47D-4521-B064-38D8450AD03F
Resource Coalition: "com.SajPanchal.MyMap"(6768)
Architecture:     arm64
Parent:           UNKNOWN [1]
PID:              81955

Event:            cpu usage
Action taken:     none
CPU:              48 seconds cpu time over 52 seconds (92% cpu average), exceeding limit of 80% cpu over 60 seconds
CPU limit:        48s
Limit duration:   60s
CPU used:         48s
CPU duration:     52s
Duration:         52.42s
Duration Sampled: 51.59s (event starts 0.61s before samples, event ends 0.22s after samples)
Steps:            22

Hardware model:   iPhone12,8
Active cpus:      6
HW page size:     16384
VM page size:     16384

Time Since Boot:  1103664s
Time Awake Since Boot: 462378s
Time Since Wake:  11420s

Total CPU Time:   59.559s
Advisory levels:  Battery -> 2, User -> 3, ThermalPressure -> 20, Combined -> 2
Free disk space:  8532.11 MB/59.57 GB, low space threshold 150 MB
Vnodes Available: 63.37% (12674/20000, 10000 allocated, 10000 soft limit)

Preferred User Language: en-CA
Country Code:     CA
Keyboards:        en_CA QWERTY, autofillsignup
OS Cryptex File Extents: 23431

Heaviest stack for the target process:
  19  ??? (libsystem_pthread.dylib + 5256) [0x21171c488]
  19  ??? (libsystem_pthread.dylib + 19580) [0x21171fc7c]
  19  ??? (<E084BF70-EA3D-346F-8B3A-73B9E0A59849> + 113664) [0x10567bc00]
  19  ??? (<E084BF70-EA3D-346F-8B3A-73B9E0A59849> + 116208) [0x10567c5f0]
  19  ??? (<E084BF70-EA3D-346F-8B3A-73B9E0A59849> + 68852) [0x105670cf4]
  19  ??? (<E084BF70-EA3D-346F-8B3A-73B9E0A59849> + 26396) [0x10566671c]
  19  ??? (<E084BF70-EA3D-346F-8B3A-73B9E0A59849> + 96324) [0x105677844]
  18  ??? (<6A83B9D4-BB8C-3670-B4DC-BF8331BA078E> + 596248) [0x105039918]
  17  ??? (dyld + 59932) [0x1aebe9a1c]
  5  ??? (dyld + 60864) [0x1aebe9dc0]


Powerstats for:   Map [81955]
UUID:             3130A94E-B368-379D-841C-570727731701
Path:             /private/var/containers/Bundle/Application/11799D10-D568-4AEE-9E34-F31A657B3034/Map.app/Map
Identifier:       com.SajPanchal.MyMap
Version:          1.3.12 (1)
Is First Party:   No
Beta Identifier:  BD3249ED-F47D-4521-B064-38D8450AD03F
Resource Coalition: 22 samples "com.SajPanchal.MyMap"(6768)
Architecture:     arm64
Parent:           UNKNOWN [1]
UID:              501
Footprint:        151.41 MB
Start time:       2024-11-10 18:10:28.666 -0500
End time:         2024-11-10 18:11:20.255 -0500
Num samples:      22 (100%)
Num threads:      2
Primary state:    18 samples Non-Frontmost App, Non-Suppressed, User mode, Effective Thread QoS Background, Requested Thread QoS Background, Override Thread QoS Unspecified, e-core
User Activity:    0 samples Idle, 22 samples Active
Power Source:     22 samples on Battery, 0 samples on AC
  19  ??? (libsystem_pthread.dylib + 5256) [0x21171c488]
    19  ??? (libsystem_pthread.dylib + 19580) [0x21171fc7c]
      19  ??? (<E084BF70-EA3D-346F-8B3A-73B9E0A59849> + 113664) [0x10567bc00]
        19  ??? (<E084BF70-EA3D-346F-8B3A-73B9E0A59849> + 116208) [0x10567c5f0]
          19  ??? (<E084BF70-EA3D-346F-8B3A-73B9E0A59849> + 68852) [0x105670cf4]
            19  ??? (<E084BF70-EA3D-346F-8B3A-73B9E0A59849> + 26396) [0x10566671c]
              19  ??? (<E084BF70-EA3D-346F-8B3A-73B9E0A59849> + 96324) [0x105677844]
                18  ??? (<6A83B9D4-BB8C-3670-B4DC-BF8331BA078E> + 596248) [0x105039918]
                  17  ??? (dyld + 59932) [0x1aebe9a1c]
                    5   ??? (dyld + 60864) [0x1aebe9dc0]
                    4   ??? (dyld + 60772) [0x1aebe9d64]
                    2   ??? (dyld + 60892) [0x1aebe9ddc]
                    2   ??? (dyld + 60756) [0x1aebe9d54]
                    1   ??? (dyld + 60920) [0x1aebe9df8]
                    1   ??? (dyld + 60880) [0x1aebe9dd0]
                    1   ??? (dyld + 60784) [0x1aebe9d70]
                    1   ??? (dyld + 60744) [0x1aebe9d48]
                      1   
                  1   ??? (dyld + 59884) [0x1aebe99ec]
                    1   ??? (dyld + 5608) [0x1aebdc5e8]
                      1   ??? (dyld + 6400) [0x1aebdc900]
                1   ??? (<6A83B9D4-BB8C-3670-B4DC-BF8331BA078E> + 596300) [0x10503994c]
                  1   ??? (dyld + 5160) [0x1aebdc428]
                    1   ??? (dyld + 5608) [0x1aebdc5e8]
                      1   ??? (dyld + 6512) [0x1aebdc970]
  3   ??? (dyld + 212680) [0x1aec0eec8]
    3   ??? (<45455F63-7B87-31BE-A798-3BA9D1EBEB5C> + 1374560) [0x106053960]
      3   ??? (<45455F63-7B87-31BE-A798-3BA9D1EBEB5C> + 1374128) [0x1060537b0]
        3   ??? (SwiftUI + 939152) [0x18d96d490]
          3   ??? (SwiftUI + 927332) [0x18d96a664]
            3   ??? (SwiftUI + 1056664) [0x18d989f98]
              3   ??? (UIKitCore + 4724148) [0x18be355b4]
                3   ??? (UIKitCore + 4009648) [0x18bd86eb0]
                  3   ??? (GraphicsServices + 4548) [0x1d52001c4]
                    3   ??? (CoreFoundation + 337968) [0x189220830]
                      2   ??? (CoreFoundation + 340008) [0x189221028]
                        2   ??? (CoreFoundation + 147352) [0x1891f1f98]
                          2   ??? (CoreFoundation + 147956) [0x1891f21f4]
                            2   ??? (SwiftUICore + 10067468) [0x248e5ae0c]
                              2   ??? (SwiftUICore + 4869844) [0x248965ed4]
                                2   ??? (SwiftUI + 3587508) [0x18dbf3db4]
                                  2   ??? (SwiftUICore + 4869588) [0x248965dd4]
                                    2   ??? (SwiftUICore + 4874192) [0x248966fd0]
                                      2   ??? (SwiftUI + 3587548) [0x18dbf3ddc]
                                        2   ??? (SwiftUI + 3552324) [0x18dbeb444]
                                          2   ??? (SwiftUICore + 10556396) [0x248ed23ec]
                                            2   ??? (SwiftUICore + 10532312) [0x248ecc5d8]
                                              2   ??? (SwiftUICore + 10646780) [0x248ee84fc]
                                                2   ??? (SwiftUI + 3552376) [0x18dbeb478]
                                                  2   ??? (SwiftUICore + 6851160) [0x248b49a58]
                                                    2   ??? (AttributeGraph + 36004) [0x1b54a7ca4]
                                                      2   ??? (AttributeGraph + 37072) [0x1b54a80d0]
                                                        2   ??? (AttributeGraph + 38156) [0x1b54a850c]
                                                          1   ??? (SwiftUICore + 5512384) [0x248a02cc0]
                                                            1   ??? (SwiftUICore + 4855744) [0x2489627c0]
                                                              1   ??? (SwiftUICore + 4857260) [0x248962dac]
                                                                1   ??? (SwiftUICore + 3757788) [0x2488566dc]
                                                                  1   ??? (SwiftUI + 2942592) [0x18db56680]
                                                                    1   ??? (SwiftUI + 6666136) [0x18dee3798]
                                                                      1   ??? (SwiftUICore + 7850952) [0x248c3dbc8]
                                                                        1   ??? (SwiftUICore + 6140004) [0x248a9c064]
                                                                          1   ??? (SwiftUICore + 6903844) [0x248b56824]
                                                                            1   ??? (libswiftCore.dylib + 3571308) [0x187b60e6c]
                                                                              1   ??? (libswiftCore.dylib + 1344000) [0x187941200]
                                                                                1   ??? (libswiftCore.dylib + 3864156) [0x187ba865c]
                                                                                  1   ??? (libswiftCore.dylib + 4081400) [0x187bdd6f8]
                                                                                    1   ??? (libswiftCore.dylib + 3907844) [0x187bb3104]
                                                                                      1   
                                                          1   ??? (SwiftUI + 2612284) [0x18db05c3c]
                                                            1   ??? (SwiftUICore + 2723624) [0x248759f28]
                                                              1   ??? (SwiftUI + 2447840) [0x18dadd9e0]
                                                                1   ??? (SwiftUICore + 6962960) [0x248b64f10]
                                                                  1   ??? (SwiftUICore + 6963984) [0x248b65310]
                                                                    1   ??? (SwiftUICore + 7395600) [0x248bce910]
                                                                      1   ??? (SwiftUICore + 6966976) [0x248b65ec0]
                                                                        1   ??? (SwiftUICore + 6973296) [0x248b67770]
                                                                          1   ??? (SwiftUI + 2721500) [0x18db206dc]
                                                                            1   ??? (SwiftUI + 2736348) [0x18db240dc]
                                                                              1   ??? (SwiftUI + 2534896) [0x18daf2df0]
                                                                                1   ??? (SwiftUICore + 4869588) [0x248965dd4]
                                                                                  1   ??? (SwiftUICore + 4874192) [0x248966fd0]
                                                                                    1   ??? (SwiftUI + 2737180) [0x18db2441c]
                                                                                      1   ??? (SwiftUI + 2680416) [0x18db16660]
                                                                                        1   ??? (SwiftUI + 15257764) [0x18e7150a4]
                                                                                          1   ??? (SwiftUICore + 10544660) [0x248ecf614]
                                                                                            1   ??? (SwiftUI + 2736932) [0x18db24324]
                                                                                              1   ??? (SwiftUI + 2553584) [0x18daf76f0]
                                                                                                1   ??? (SwiftUI + 11429384) [0x18e36e608]
                                                                                                  1   ??? (SwiftUI + 11430568) [0x18e36eaa8]
                                                                                                    1   ??? (libswiftCore.dylib + 875844) [0x1878ced44]
                                                                                                      1   
                      1   ??? (CoreFoundation + 341492) [0x1892215f4]
                        1   ??? (CoreFoundation + 342288) [0x189221910]
                          1   ??? (CoreFoundation + 415460) [0x1892336e4]
                            1   ??? (LocationSupport + 38308) [0x1aa3e65a4]
                              1   ??? (CoreLocation + 68484) [0x196ab5b84]
                                1   ??? (CoreLocation + 102788) [0x196abe184]
                                  1   ??? (<45455F63-7B87-31BE-A798-3BA9D1EBEB5C> + 617744) [0x105f9ad10]
                                    1   ??? (<45455F63-7B87-31BE-A798-3BA9D1EBEB5C> + 617664) [0x105f9acc0]
                                      1   ??? (<45455F63-7B87-31BE-A798-3BA9D1EBEB5C> + 571096) [0x105f8f6d8]
                                        1   ??? (Combine + 68032) [0x1925679c0]
                                          1   ??? (Combine + 625056) [0x1925ef9a0]
                                            1   ??? (Combine + 624932) [0x1925ef924]
                                              1   ??? (Combine + 623640) [0x1925ef418]
                                                1   ??? (Combine + 68840) [0x192567ce8]
                                                  1   ??? (Combine + 69764) [0x192568084]
                                                    1   ??? (Combine + 70064) [0x1925681b0]
                                                      1   ??? (SwiftUICore + 6412548) [0x248ade904]
                                                        1   ??? (SwiftUICore + 1870620) [0x248689b1c]
                                                          1   ??? (libswiftCore.dylib + 3983376) [0x187bc5810]
                                                            1   

  Binary Images:
           0x104bc0000 -                ???  com.SajPanchal.MyMap 1.3.12 (1) <3130A94E-B368-379D-841C-570727731701>  /private/var/containers/Bundle/Application/11799D10-D568-4AEE-9E34-F31A657B3034/Map.app/Map
           0x104fa8000 -                ???  ???                             <6A83B9D4-BB8C-3670-B4DC-BF8331BA078E>
           0x105660000 -                ???  ???                             <E084BF70-EA3D-346F-8B3A-73B9E0A59849>
           0x105f04000 -                ???  ???                             <45455F63-7B87-31BE-A798-3BA9D1EBEB5C>
           0x1877f9000 -        0x187d9afff  libswiftCore.dylib              <1AE81AC9-024C-33C5-9E78-CCFA639C5F06>  /usr/lib/swift/libswiftCore.dylib
           0x1891ce000 -        0x189710fff  CoreFoundation                  <1532D3D8-9B3B-3F2F-B35F-55A20DDF411B>  /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
           0x18b9b4000 -        0x18d887fff  UIKitCore                       <575E5140-FA6A-37C2-B00B-A4EACEDFDA53>  /System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore
           0x18d888000 -        0x18eb7cfff  SwiftUI                         <9F67C19C-FCDE-3E97-9FC2-3BBA36998297>  /System/Library/Frameworks/SwiftUI.framework/SwiftUI
           0x192557000 -        0x192682ff7  Combine                         <2C317C8F-DE09-3B06-A459-8AC94C07CC10>  /System/Library/Frameworks/Combine.framework/Combine
           0x196aa5000 -        0x196d04fff  CoreLocation                    <3A46AF8C-B1E5-3941-8387-88724A3923D9>  /System/Library/Frameworks/CoreLocation.framework/CoreLocation
           0x1aa3dd000 -        0x1aa412fff  LocationSupport                 <344B3168-174E-34A1-B409-76D55DED3F6C>  /System/Library/PrivateFrameworks/LocationSupport.framework/LocationSupport
           0x1aebdb000 -        0x1aec5e99f  dyld                            <3060D36A-16CE-3C3A-9258-3881459F5714>  /usr/lib/dyld
           0x1b549f000 -        0x1b54e2fff  AttributeGraph                  <6DFBF865-450C-3897-A13F-C9A348DB0267>  /System/Library/PrivateFrameworks/AttributeGraph.framework/AttributeGraph
           0x1d51ff000 -        0x1d5207fff  GraphicsServices                <8425EA11-000E-3E5E-8ABC-BDDF3FF3FA32>  /System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices
           0x21171b000 -        0x211727ff3  libsystem_pthread.dylib         <3CA98E38-8EEE-3C26-9862-C5F66AAD93C0>  /usr/lib/system/libsystem_pthread.dylib
           0x2484c1000 -        0x24904ffff  SwiftUICore                     <E693F599-F256-31B2-A6EF-C4C1334972B7>  /System/Library/Frameworks/SwiftUICore.framework/SwiftUICore

here is the report I found. there is no code-related crash here. it seems like there are some performance issues!

My App crashes run-time occasionally when I use AVFoundation and related code
 
 
Q