Search code examples
swiftparse-platformparse-serverios-app-extension

How to check if Parse initialized already


So I created a Keyboard app extension that uses Parse to get some needed data. I initialized Parse after the keyboard loads like this:

func connectParser() {
// Initialize Parse
        let configuration = ParseClientConfiguration {
            $0.applicationId = "BlahBlahBlah123456"
            $0.clientKey = "BlahBlahBlah123456"
            $0.server = "https://parseapi.back4app.com"
        }
        Parse.initialize(with: configuration)
}

note: Initialization is normally done in AppDelegate, but since this is an App Extension I did it in the main InputView that gets loaded first

The problem occurs when the user switches out of the keyboard after loading it and then tries to switch back to the keyboard. The extension crashes and I get the following error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Parse is already initialized.'

How do I check to see if Parse is initialized already so I don't re-initialize it and cause a crash?


Solution

  • So I didn't find any real solutions to this anywhere, but I did find my own solution and I'll keep it here and answer my own question in case anyone else runs into this:

    Basically I check to see if Parse.currentConfiguration() == nil

    if it does, then I know Parse hasn't been initialized yet. I don't know if this is the best way of going about this, so if you have a better alternative, please add it as an answer.

    Final function looks like this:

    func connectParse() {
        
        if Parse.currentConfiguration() == nil {
            // Initialize Parse
            let configuration = ParseClientConfiguration {
                $0.applicationId = "BlahBlahBlah123456"
                $0.clientKey = "BlahBlahBlah123456"
                $0.server = "https://parseapi.back4app.com"
            }
            Parse.initialize(with: configuration)
        }
    }