Periksa apakah UserDefault ada - Swift

87

Saya mencoba untuk memeriksa apakah default pengguna ada, terlihat di bawah ini:

func userAlreadyExist() -> Bool {
    var userDefaults : NSUserDefaults = NSUserDefaults.standardUserDefaults()

    if userDefaults.objectForKey(kUSERID) {
        return true
    }

    return false
}

Namun, tidak peduli apa itu akan selalu kembali benar bahkan ketika objek tersebut belum ada? Apakah ini cara yang tepat untuk memeriksa keberadaan?

Ryan
sumber

Jawaban:

129

Astun punya jawaban yang bagus. Lihat di bawah untuk versi Swift 3.

func isKeyPresentInUserDefaults(key: String) -> Bool {
    return UserDefaults.standard.object(forKey: key) != nil
}
pengguna7248923
sumber
29

I copy/pasted your code but Xcode 6.1.1 was throwing some errors my way, it ended up looking like this and it works like a charm. Thanks!

func userAlreadyExist(kUsernameKey: String) -> Bool {
    return NSUserDefaults.standardUserDefaults().objectForKey(kUsernameKey) != nil
}
Astun
sumber
Worked! But you forgot the parameter so I added it in.
Jesse Onolemen
21

Ya ini adalah cara yang tepat untuk memeriksa optionalmemiliki nilatau nilai apapun objectForKeykembali metode AnyObject?yang Implicit optional.

Jadi jika userDefaults.objectForKey(kUSERID)memiliki nilai apa pun daripada yang dievaluasi true. jika userDefaults.objectForKey(kUSERID)memiliki nilnilai daripada yang dievaluasi false.

Dari panduan pemrograman cepat

Jika Pernyataan dan Pembongkaran Paksa Anda dapat menggunakan pernyataan if untuk mengetahui apakah opsional berisi nilai. Jika sebuah opsional memang memiliki nilai, ia mengevaluasi ke true; jika tidak memiliki nilai sama sekali, ia mengevaluasi ke salah.

Sekarang ada bug di simulator daripada setelah kunci pengaturan di userDefaultsmereka selalu tetap disetel tidak peduli Anda menghapus aplikasi Anda. Anda perlu mengatur ulang simulator.

Reset your Simulator check this method before setting key in userDefaults or remove key userDefaults.removeObjectForKey(kUSERID) from userDefaults and it will return NO.On devices it is resolved in iOS8 beta4.

codester
sumber
" objectForKey method returns AnyObject! which is Implicit optional " This is wrong it returns AnyObject?
Leo Dabus
1
@LeoDabus Swift has changed so many times. Thanks BTW I have changed that.
codester
as of 10/25/2016 the line in the docs now say "You can use an if statement to find out whether an optional contains a value by comparing the optional against nil. You perform this comparison with the “equal to” operator (==) or the “not equal to” operator (!=)." Xcode 7.3.1 will show a compilation error if you try to if anOptional { } and it will suggest you test using == nil or != nil
wyu
15

This is essentially the same as suggested in other answers but in a more convenient way (Swift 3+):

extension UserDefaults {
    static func contains(_ key: String) -> Bool {
        return UserDefaults.standard.object(forKey: key) != nil
    }
}

usage: if UserDefaults.contains(kUSERID) { ... }

Sir Codesalot
sumber
then it makes sense to make the function static because you're accessing a singleton standard: static func contains(key: String) -> Bool. Otherwise, makes more sense to make return self.object(forKey: key) != nil
Nomad Developer
5

Simple Code to check whether value stored in UserDefault.

let userdefaults = UserDefaults.standard
if let savedValue = userdefaults.string(forKey: "key"){
   print("Here you will get saved value")       
} else {
   print("No value in Userdefault,Either you can save value here or perform other operation")
   userdefaults.set("Here you can save value", forKey: "key")
}
Sudhi 9135
sumber
2

for swift 3.2

func userAlreadyExist(kUsernameKey: String) -> Bool {
    return UserDefaults.standard.object(forKey: kUsernameKey) != nil
}
Johny D Good
sumber
0
public class PreferencesUtils {

    private init() {

    }

    public static func setBoolData(boolValue: Bool, dataName: String) {
        UserDefaults.standard.set(boolValue, forKey: dataName)
    }

    public static func getBoolData(dataName: String)-> Bool{

        let defaults = UserDefaults.standard

        if(defaults.value(forKey: dataName) != nil) {
            return defaults.value(forKey: dataName)! as! Bool

        } else {
            return false
        }
    }

    public static func saveStringData(data: String, dataName: String){
        let preferences = UserDefaults.standard
        preferences.set(data, forKey: dataName)
        let didSave = preferences.synchronize()
        if !didSave {
            debugPrint("Not saved yet")
        }
    }

    public static func getSavedStringData(dataName: String)-> String{
        let defaults = UserDefaults.standard
        if(defaults.value(forKey: dataName) != nil){
            return defaults.value(forKey: dataName) as! String
        } else {
            return ""
        }
    }

    public static func saveIntData(data : Int, dataName: String){
        let preferences = UserDefaults.standard
        preferences.set(data, forKey: dataName)
        let didSave = preferences.synchronize()
        if !didSave {
            debugPrint("Not saved yet")
        }
    }

    public static func getSavedIntData(dataName: String) -> Int {
        let defaults = UserDefaults.standard
        if(defaults.value(forKey: dataName) != nil){
            return defaults.value(forKey: dataName) as! Int
        }else{
            return 0
        }
    }

}

Or you can try this library: Link

Jamil Hasnine Tamim
sumber
0
func keyExists(key: String) -> Bool {
    guard let _ = UserDefaults.standard.object(forKey: key) {
     return false;
    }

   return true;
}
Andrea Leganza
sumber
Harap jangan hanya memposting kode sebagai jawaban, tetapi berikan juga penjelasan tentang fungsi kode Anda dan cara kode menjawab pertanyaan. Jawaban dengan penjelasan biasanya lebih bermanfaat dan berkualitas lebih baik, dan lebih cenderung menarik suara positif.
Mark Rotteveel
0

override func viewDidLoad () {

super.viewDidLoad ()

jika UserDefaults.standard.string (forKey: "CHARRY") == "CHARRY" {

 lb.text = "CHARRY"

 im.image = UIImage(named: "CHARRY")

}}

@IBAction func PressedCar(_ sender: UIButton){

 lb.text = "CHARRY"

 im.image = UIImage(named: "CHARRY")

 UserDefaults.standard.set("CAR", forKey: "CHARRY")


}
hamayun zeb
sumber
0

Banyak solusi di sini yang valid. Tetap saja, saya pikir mereka menyelesaikan masalah yang salah.

Biasanya, kode seperti ini digunakan untuk memeriksa apakah suatu nilai ditetapkan sehingga nilai default lain dapat digunakan:

if isKeyPresentInUserDefaults(key: "username") {
    return UserDefaults.standard.string(forKey: "username")
} else {
    return "No username was set"
}

You shouldn't care if a key is set or not. There is a far more elegant approach for having default values in UserDefaults:

UserDefault.standard.register(defaults: ["username": "No username was set"])

If you run this code at app launch, subsequent calls to UserDefaults.standard.string(forKey: "username") will return the default value of "No username was set" if no value was set for the key yet.

Xavier Lowmiller
sumber