Search code examples
iosswiftswift3eventkit

EKEvent endDate is nil; unable to check implicit unwrapped optional without crashing the app


In my code I retrieve an Event from an EKEventstore and then I map the values into a custom Swift Object

public class WPEvent: NSObject, NSCopying, Comparable {

let ddLogLevel = DDLogLevel.verbose

static let vacationPrefix = "Vacation"
static let visitReportPrefix = "* "

public var eventIdentifier: String
public var calendar: EKCalendar
public var title: String
public var allDay: Bool
public var detached: Bool
public var unsafed: Bool
public var creationDate: Date?
public var startDate: Date
public var endDate: Date
public var timeZone: TimeZone?
public var location: String?

public init(event: EKEvent) {
    eventIdentifier = event.eventIdentifier
    calendar = event.calendar
    title = event.title
    allDay = event.isAllDay
    detached = event.isDetached
    unsafed = event.isNew
    creationDate = event.creationDate
    startDate = event.startDate
    endDate = event.endDate
    timeZone = event.timeZone
    location = event.location

    super.init()
}

And in all my tests this passes and is fine. Recently however I start getting some strange crash reports like this

Hardware Model:      iPad5,4
OS Version:          iOS 10.2.1 (14D27)
Report Version:      105

Exception Type:  SIGTRAP
Exception Subtype: undefined

Thread 12 name:
Thread 12 Crashed:
0   libswiftFoundation.dylib         0x000000010295179c 0x102948000 + 38812
1   CalendarSyncEngine               0x0000000101399520 specialized WPEvent.init(event:) (WPEvent.swift:49)
2   CalendarSyncEngine               0x00000001013844b8 specialized EKEventStoreWrapper.events(withStart:end:salesRepId:) (EventStore.swift:0)
3   CalendarSyncEngine               0x00000001013846fc specialized EKEventStoreWrapper.events(forDate:salesRepId:) (EventStore.swift:0)

Line 49 is where the endDate is assigned, and if it crashes then always there.

Is it possible to get a nil-Enddate even if the EventKit API lists it as implicit unwrapped optional?

Obviously yes (thanks for the comments)

As this value is provided as such from an Apple framework, how can I check if this is nil without having a crash at that point?

Update: Reproducing is quite simple as stated in the AppleDoc "@discussion This will be nil for new events until you set it." So simply don't set it, but I still can't figure out how to check if this event has no enddate without crashing it.


Solution

  • I ended up in adding a little piece of Objective-C code into my Swift framework that checks on nil and fills the dates with some values to avoid the crash