Khoury Khoury - 1 year ago 144
Swift Question

How to check a single time if UserDefaults is empty

My app counts the days between a date and NSDate(). When I released it, a user could only save one date, a title and a background image.

Now I have a UICollectionView with the option to save more than one date, and it will create a cell by appending a date, title and image string to their respective arrays.

The app has been completely changed, so I'm struggling with how to check whether a user has saved a date, and if they have, add that info to the arrays to create a cell.

But, I want this to only been checked once - the first time the app is opened from update or fresh install.

Here is my thinking about it, it doesn't work by the way.

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell

if userDefault.objectForKey("day") == nil {
} else {
// Add the first date created from previous version
let day = userDefault.objectForKey("day") as? String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMMM yyyy hh:mm a"
let date = dateFormatter.dateFromString(day!)!
let date1 = dateFormatter.stringFromDate(date)

// Add the since text
let text = userDefault.objectForKey("sinceText") as? String

//Add the image background
let image = userDefault.objectForKey("khoury") as! String

What happens with the code above is it returns nil. I am expecting it to create the first cell, so that the user can see the date they have saved.

Answer Source

You can use another boolean value in NSUserDefaults to detect the first run:

let defaults = NSUserDefaults.standardUserDefaults()

if (!defaults.boolForKey("migrated")) {
    defaults.setBool(true, forKey: "migrated")
    // ... anything else
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download