Jake Walker Jake Walker - 4 years ago 115
iOS Question

How to run data only once in whole app's life?

I want to set some data into NSUserdefaults, but I only want it to be set at the start. I have a feeling this would go somewhere into AppDelegate.

For example, I want to put a "isLoggedIn" bool check, but I need to set it equal false before runtime, so that it can check it at runtime.

Answer Source

NSUserDefaults (or UserDefaults in Swift 3) has a function register(defaults:) that lets you provide a dictionary containing "default defaults" or starting defaults. That's what you need. I usually put a call to register(defaults:) in the App delegate's initialize method so it's called very early in the app startup, before any of your instance methods get called. The initialize method in your app delegate might look like this in Swift:

func initialize() {
  let dict: [String: Any] = [
    "Key1": "value1",
    "Key2": 3
    "isLoggedIn": false]
  UserDefaults.standard.register(defaults: dict)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download