-2

I am creating an app that requires to have a UserDefaultManager. But unfortunately it shows an error:

Use of unresolved identifier 'UserDefaults'

I tried to solve it by declaring a variable like:

let UserDefaults = NSUserDefaults.standardUserDefaults()

but it is still not working for me. Attached below are my codes for your references. Hope you can help me. By the way I am using xcode 10.

struct UserDefaultsManager {
    private static let isLoggedInKey = "com.example.key.isLoggedIn"

    //  let UserDefaults = NSUserDefaults.standardUserDefaults()

    static func login() {
        UserDefaults.standard.setValue(true, forKey: isLoggedInKey)
        UserDefaults.standard.synchronize()
    }

    static func logout() {
        UserDefaults.standard.setValue(false, forKey: isLoggedInKey)
        UserDefaults.standard.synchronize()
    }

    static func isLoggedIn() -> Bool {
        return UserDefaults.standard.bool(forKey: isLoggedInKey)
    }
}
AtulParmar
  • 4,358
  • 1
  • 24
  • 45
Titus
  • 349
  • 4
  • 19

1 Answers1

0

No, it isn't deprecated. This is my code: save data

    let user = UserDefaults.standard
    user.set(userJson.email, forKey: "email")
    user.set(userJson.id, forKey: "id")
    user.set(userJson.username, forKey: "user")

and get data

    let userDefault = UserDefaults.standard
    getEmailToCheck = userDefault.string(forKey: "email") ?? ""
    user_id = userDefault.string(forKey: "id") ?? ""

and you don't need to import Foundation directly in your swift file. Hope this helps you.

Quyen Anh Nguyen
  • 1,204
  • 13
  • 21