1

This may well be me being ignorant of swift but I am confused..

I have the following (simplified) code - note I have pulled a lot out of it as it (generally) functions as expected:

engine = AVAudioEngine() //engine being a class variable

AVAudioUnit.instantiate(with: mixerDesc, options: [.loadOutOfProcess], completionHandler: {(audioUnit, auError) in
    //configure matrix mixer
    self.matrixMixer = au
    engine.attach(au)

    print("make connections")
    engine.connect(engine.inputNode, to: au, format: inputFormat)
    engine.connect(au, to: engine.mainMixerNode, format: inputFormat)
    print("connections done")

    try! engine.start()
} 

This code works 99% of the time, however there are occasions (mainly when the default input/output device changes) that an error is being generated when the connections are being made. The thing I don't understand is that this error is causing the function to exit at the point the error happens (when the connections are made), but doesn't cause the application to terminate - I am asuming this is because the error is just killing that thread.

Is there any way to catch that error? I've tried adding a defer {} to the start of the function, but this isn't called either. It's frustrating as it's meaning the application is getting out of sync and I'm not clear how to catch it.

FYI the error being thrown is:

2020-05-31 22:33:22.219189+0100 StageSound[20887:289670] [General] required condition is false: IsFormatSampleRateAndChannelCountValid(hwFormat)
2020-05-31 22:33:22.221812+0100 StageSound[20887:289670] [General] (
    0   CoreFoundation                      0x00007fff332f1be7 __exceptionPreprocess + 250
    1   libobjc.A.dylib                     0x00007fff6c0c95bf objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff3331ad98

and the crash log continues..

1 Answers1

1

It looks like an NSException is thrown from Objective-C code. You cannot catch NSExceptions directly from Swift but there is a way by creating a bridge between Objective-C and Swift. This way you can convert NSException into something Swift understands (NSError for example).

For details about this bridging have a look at: https://stackoverflow.com/a/36454808

Ruurd Adema
  • 920
  • 7
  • 17
  • 1
    Brilliant thanks - that was exactly it. I ended up using this package https://github.com/sindresorhus/ExceptionCatcher which seems to solve my problems. – Richard Williamson Jun 02 '20 at 13:33