Use userdeafult in iOS project in better way

Method 1: You could declare a computed property for getting/setting the value from the user defaults

Create Utility.swift class

var userDeviceToken: String {
      get {
           if let userAppID = UserDefaults.standard.object(forKey: "userDeviceToken") as? String {
               return userDeviceToken

           } else {
               return ""
           }
       }
       set {
           UserDefaults.standard.set(newValue, forKey: "userDeviceToken")
           UserDefaults.standard.synchronize()
       }
   }

and you can set value anywhere ex. userDeviceToken = “12345” and can get that value anywhere directly ex. print(“userDeviceToken”)

Method 2: Create common methods for set, get and remove

func setValueToDefaults(key:String, value:AnyObject){
    self.removeKeyValueFromDefaults(Key:key)
    UserDefaults.standard.set(value, forKey: key)

}

func getValueFromDefaults(key:String) ->AnyObject?{

    if((UserDefaults.standard.value(forKey: key)) != nil){

        let value:AnyObject = UserDefaults.standard.value(forKey: key)! as AnyObject

        return value
    }else{

        return nil
    }

}

func removeKeyValueFromDefaults(Key:String){

    let defaults = UserDefaults.standard
    defaults.removeObject(forKey: Key)
    defaults.synchronize()

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s