Jupit Kumar Jupit Kumar - 1 year ago 162
Swift Question

Swift - NSUserDefaults Having value or not?

My App crashing due to Empty or null value from NSUserDefaults. How to validate NSUSerdefaults Having value or not?

let empName = NSUserDefaults.standardUserDefaults().stringForKey("EMP_NAME")

lblUserName.text = "Hello I'm \(empName!)"

Answer Source

Check below possible conditions.

1. Check NSUserDefaults is null:

if(NSUserDefaults.standardUserDefaults().objectForKey("EMP_NAME") == nil)

2. Check NSUserDefaults String is null or Empty:

if((NSUserDefaults.standardUserDefaults().stringForKey("EMP_NAME")) == "" || NSUserDefaults.standardUserDefaults().stringForKey("EMP_NAME") == nil)
   print("NULL or Empty String")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download