Search code examples
iosswiftsqlite.swift

How to call a class only the first time i access an iOS app


I want to create database when i access the app for the first time.

As you know, Swift has an AppDelegate.swift class with @UIApplicationMain, and it means main() class.

If i want to create database when i first access the app and not the next time i access it, what should i do?

Can i change the AppDelegate.swift? (i don't know it's good way)

Or use flag? (i think whenever i access the app, that flag will initialize... should i save the flag in the local database??? but that time, there will be no database...)

In addition, I'm using Sqlite.swift.

if you need my codes to understand question, comment me!


Solution

  • simple solution to know if app already launched:

    let alreadyLaunched = UserDefaults.standard.bool(forKey: "AppLauch")
    
    if !alreadyLaunched {
        // setup everything needed
        //....
        UserDefaults.standard.set(true, forKey: "AppLauch")
        UserDefaults.standard.synchronize()
    }
    

    You're completely right, put it in AppDelegate didFinishLaunchingWithOptions before returning.

    NOTE: this method does not guarantee your database complete setup (check your database API related methods to get sure), just tells this app launched before or not.