Sunday, March 29, 2015

Parsing a date out of JSON in Swift

For most of the APIs you'll deal with you'll get the date back in a For most of the APIs you'll deal with you'll get the date back in a format like this:
In Objective-C it was pretty easy assume the interval is the value above,
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval/1000.0];

NSDateFormatter* df_local = [[NSDateFormatter alloc] init];
[df_local setTimeZone:[NSTimeZone timeZoneWithName:@"CST"]];
[df_local setDateFormat:@"MM-dd"];    

NSString* ts_local_string = [df_local stringFromDate:date];
This would give you a formatted date string in the timezone you request.
In Swift it wasn't as straight forward.
Originally I attempted this:
var meetups = [Meetup]()
for meetupDictionary in (meetupsJsonArray as Array<Dictionary<String, AnyObject>>) {
    let eventName = meetupDictionary[self.nameKey]! as String
    let eventId = meetupDictionary[self.idKey]! as String
    let timeValue = meetupDictionary[self.timeKey]! as Int
    let timeValueAsDouble = Double(timeValue/1000.0)
    let date = NSDate(timeIntervalSince1970: timeValueAsDouble)
    let meetup = Meetup(title: eventName, eventId: eventId, date: date)
That worked, actually (well not the timezoning, but the date-time anyway).
But only on a 64 bit device/simulator. On an iPhone 5/4s it was giving a strange value for the year. As you would guess, it had to do with as Int. I won't explain it here, but the blog sketchyTech explains how numbers and primitives are handled in Swift.

Swift by the numbers, the long and short of it

The correct way was to change the time parsing lines to this:
let timeValueAsNSNumber = meetupDictionary[self.timeKey]! as NSNumber
let timeValue = timeValueAsNSNumber.doubleValue/1000.0
let date = NSDate(timeIntervalSince1970: timeValue)
Even with the new offerings of Swift, you still have to use aspects of the CocoaTouch framework like NSNumber. This gave the correct date and time on a 32 and 64 bit devices.

No comments:

Post a Comment

Mvvm on Mobile?

Here's my talk from Houston Tech Fest 2017. Recorded Talk: Slides: