0

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!

doori
  • 85
  • 1
  • 6
  • 1
    use user defaults to store your flag. – Dilan Apr 14 '20 at 09:14
  • 1
    Yes, set a Boolean to true in user defaults after you have created the database. Before creating the database check if the user defaults value is true. If it is, skip database creation. – Paulw11 Apr 14 '20 at 09:19

1 Answers1

0

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.

zzmasoud
  • 164
  • 1
  • 8
  • Thank you for letting me know. i have one more question. i want to initialize database whenever i build the project. but if i use UserDefaults, it didn't work. i mean, isn't doing 'build the project' to start app at first time? – doori Apr 14 '20 at 09:54