Jupit Kumar Jupit Kumar - 4 months ago 29x
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!)"


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")