Reputation: 431
I am trying to save some variable to NSUserDefaults
when tapping on a UICollectionView
cell, but I get the following error.
fatal error: unexpectedly found nil while unwrapping an Optional value
Here is the code I am using when a cell is tapped.
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// handle tap events
let text = Globals.sinceLabelArray[indexPath.item]
userDefaults.setObject(text, forKey: "sinceText")
let image = String(Globals.imagesArray[indexPath.item])
userDefaults.setObject(image, forKey: "khoury")
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let daydate = Globals.datesArray[indexPath.item] as String
userDefaults.setObject(daydate, forKey: "day")
performSegueWithIdentifier("menutohome", sender: nil)
}
Here is the view it impacts, and how.
let day = userDefault.objectForKey("day") as? NSDate
let date1 = day
let date2 = NSDate()
let diffDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second], fromDate: date1!, toDate: date2, options: NSCalendarOptions.init(rawValue: 0))
Thanks
Upvotes: 1
Views: 204
Reputation: 81
I think you're setting dayDate as String
let daydate = Globals.datesArray[indexPath.item] as String // <- String
userDefaults.setObject(daydate, forKey: "day")
While when you called it back as NSDate
let day = userDefault.objectForKey("day") as? NSDate // <- NSDate
UPDATE:
You can save the dateObject as String first into NSUserDefaults. Once you want to use it, then use dateFormatter to make it as NSDate.
Example:
When you call it back from NSUserDefaults
let day = userDefault.objectForKey("day") as? String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // this format must equal to what it returns from the server
let dayDate: NSDate = dateFormatter.dateFromString(day)
print(dayDate) // your NSDate
Upvotes: 1
Reputation: 5450
If you are not sure if a variable is nil or not try and use conditional statement before using it for example:
Instead of:
let text = Globals.sinceLabelArray[indexPath.item]
userDefaults.setObject(text, forKey: "sinceText")
use:
if let text = Globals.sinceLabelArray[indexPath.item] {
userDefaults.setObject(text, forKey: "sinceText")
} else {
print("error has happened here")
}
Upvotes: 1