Store CLLocation Manager Values in Device swift

2019-09-13 15:32发布

问题:

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?

回答1:

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")

    userDefaults.synchronize()

    // **retrieving**:
    //use optional binding for objects to check if it's nil
    if let myRetrievedString = userDefaults.objectForKey("kMyString") as? String {
        print(myRetrievedString)
    } 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")


回答2:

Tadaaaaaa:

func arrayOfDictionaries() {
        var offline:[[String:AnyObject]] = []
        offline.append(["LATITUDE: ": userLocation.coordinate.latitude, "LONGITUDE: ": userLocation.coordinate.longitude, "SPEED: ": userLocation.speed])

        NSUserDefaults().setObject(offline, forKey: "offLine")

        if let offLinePositions = NSUserDefaults().arrayForKey("offLine") as? [[String:AnyObject]] {
            //print(offLinePositions)  


            for item in offLinePositions {
                print(item["LATITUDE: "]! as! NSNumber)  // A, B
                print(item["LONGITUDE: "]! as! NSNumber)  // 19.99, 4.99
                print(item["SPEED: "]! as! NSNumber)  // 1, 2
            }
        }

    }