-4

I am creating an app and I would like user to be logged in all the way after they register an account with the app until the user decides to delete the account. It works something like whatsapp. Am i correct to use userdefault to store what the user key in during registration? Then lets say i have a registerviewcontroller.swift and a userviewcontroller.swift, how do i call the userdefault user data stored in registerviewcontroller.swift from userviewcontroller.swift?

I am using ios 11 and swift 4. Please help. Thank you.

noob
  • 11
  • 5

5 Answers5

0

in registerviewcontroller.swift declare something like this.

let userName=dict["user_name"] as? String

 UserDefaults.standard.set(userName, forKey: "user_name")

from userviewcontroller.swift use like this

 let userName  =  UserDefaults.standard.string(forKey: "user_name")
Ram
  • 858
  • 1
  • 14
  • 19
0

to save and retrieve the userinfo in userdefault you need to something like

class Helper {
 static func setUserInfo( userinfo: UserInfo?) {

    if let info = userinfo {

        UserDefaults.standard.setValue(NSKeyedArchiver.archivedData(withRootObject: info), forKey: "USERINFO")

    }
    else {

        UserDefaults.standard.setValue(nil, forKey: "USERINFO")

    }

    UserDefaults.standard.synchronize()

}

static func getUserInfo() -> UserInfo? {

    if let data = UserDefaults.standard.value(forKey: "USERINFO") {

        return (NSKeyedUnarchiver.unarchiveObject(with: data as! Data) as! UserInfo)

    }

    return nil

}
 }

and here is the userInfo class //here i am using objectmapper lib, you might/not need accordingly

class UserInfo: NSObject, NSCoding, Mappable {

var patientId: String?
var authKey : String?



override init() {
    super.init()
}

required init?(map: Map){

}

func mapping(map: Map) {
    patientId <- map["patient_id"]
authKey <- map["authKey"]

}

required init?(coder aDecoder: NSCoder) {
    patientId = aDecoder.decodeObject(forKey: "patientId") as? String
    authKey = aDecoder.decodeObject(forKey: "authKey") as? String

}

func encode(with aCoder: NSCoder) {
    aCoder.encode(patientId, forKey: "patientId")
    aCoder.encode(authKey, forKey: "authKey")

}


}

now in your registration view controller, in viewdidload method

if let _ = Helper.getUserInfo() { // there is user logged in, i.e. user installed the app and registered earlier
        if let mainModuleTabBar = StoryboardHelper.mainModuleStory().instantiateViewController(withIdentifier: MyTabBarController.controllerIdentifier) as? MyTabBarController {
            let window = (UIApplication.shared.delegate as! AppDelegate).window
            window?.rootViewController = mainModuleTabBar
            window?.makeKeyAndVisible()
        }
        return
    }
Ashwin Shrestha
  • 518
  • 3
  • 17
0

What ever you store in Userdefaults is accessible in whole application. It is related to any specific view controller.

Userdefaults are stored in form of plist file in Data Container of your application.

To Store User Defaults

UserDefaults.standard.setValue("<Value>", forKey: "<Key>")
UserDefaults.standard.synchronize()

To Access User Defaults

UserDefaults.standard.value(forKey: "<Value>")
Priya
  • 735
  • 5
  • 10
  • 3
    UserDefaults.standard.synchronize() is not needed. – kd02 Mar 05 '18 at 11:55
  • What @kd02 wrote is spelled out on the [documentation page for UserDefaults.synchronize()](https://developer.apple.com/documentation/foundation/userdefaults/1414005-synchronize): "this method is unnecessary and shouldn't be used" – jcsahnwaldt Reinstate Monica Jun 29 '19 at 17:12
0

Save integers, booleans, strings, arrays, dictionaries, dates and more, but you should be careful not to save too much data because it will slow the launch of your app in Swift 4

let defaults = UserDefaults.standard
defaults.set(25, forKey: "intkey")
defaults.set(true, forKey: "boolkey")
defaults.set(CGFloat.pi, forKey: "floatkey")

defaults.set("Paul Hudson", forKey: "stringkey")
defaults.set(Date(), forKey: "datestore")
P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
-1

To save and retrieve the value in userdefaults , below util methods you should use.

import UIKit

class PersistanceManager: NSObject {

/// Set value in user defaults
///
/// - Parameter key: key for which value to be saved in user defaults
/// - Returns: value to save in user default
static func getPersistenceValueForKey(key : String) -> Any?{
    if let value = UserDefaults.standard.value(forKey: key){
        return value
    }
    return nil
}


/// Retrieve value from user default for the key
///
/// - Parameters:
///   - value: value fetched for the key from user defaults
///   - key: key for which value to be retrived
static func setPersistence(value : Any? , forKey key:String){
    if !key.isEmpty {
        if let value = value {
            UserDefaults.standard.setValue(value, forKey: key)
            UserDefaults.standard.synchronize()
        }
        else {
            UserDefaults.standard.removeObject(forKey: key)
        }
        //Doing the syncronize in async queue. performance Fix
        let persistenceQueue = DispatchQueue(label: "ID")
        persistenceQueue.async(execute: {() -> Void in
            UserDefaults.standard.synchronize()
        })
    }
  }
}
  • 1
    `.synchronize()` is obsolete, useless and can cause issues. This is explained in the current documentation. Please remove this line from your answer (and from your codebases). – Eric Aya Jul 18 '18 at 09:09
  • What @ayaio wrote is spelled out on the [documentation page for UserDefaults.synchronize()](https://developer.apple.com/documentation/foundation/userdefaults/1414005-synchronize): "this method is unnecessary and shouldn't be used" – jcsahnwaldt Reinstate Monica Jun 29 '19 at 17:13