ggirao ggirao - 1 year ago 114
Swift Question

Store CLLocation Manager Values in Device swift

I'm building an app that sends (every x seconds) to an API the location values with some extra values (session, ID, etc) that is working nice (see here Update CLLocation Manager on another method). But for improved feature, we are considering the device can lost (for some amount of time) internet connection. So I need to temporary store all values and when reconnected send them again to the API.

I'm considering several ways to do it:

  • Core Data (difficult implementation)

  • Realm (very little experience)

  • NSDisctionary

Can anyone suggest (and show how, if possible) the best way to implement this feature?

Answer Source

If you want to store a some of non-sensitive values (such as a password), I suggest to use NSUserDefaults, you can easily use it like a dictionary:

Note: Swift 2 Code.

For example:

    // shared instance (singleton)
    let userDefaults = NSUserDefaults.standardUserDefaults()

    // **storing**:
    let myString = "my string"
    userDefaults.setObject(myString, forKey: "kMyString")

    let myInt = 101
    userDefaults.setInteger(myInt, forKey: "kMyInt")

    let myBool = true
    userDefaults.setBool(myBool, forKey: "kMyBool")


    // **retrieving**:
    //use optional binding for objects to check if it's nil
    if let myRetrievedString = userDefaults.objectForKey("kMyString") as? String {
    } else {
        // if it's nil
        print("there is now value for key: kMyString")

    // if there is no value for key: kMyInt, the output should be zero by default
    let myRetrievedInt = userDefaults.integerForKey("kMyInt")

    // if there is no value for key: kMyBool, the output should be false by default
    let myRetrievedBool = userDefaults.boolForKey("kMyBool")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download