简体   繁体   中英

Setting a reminder in the background of an iOS app

I am trying to create a reminder when a user enters a region. The code works for creating a reminder when the app is open. But when I call the same code when the app is in the background I get fatal error: unexpectedly found nil while unwrapping an Optional value. The code below is being called in the AppDelegate.

var eventStore: EKEventStore!
func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) {
                let reminder = EKReminder(eventStore: self.eventStore) //This is where I get the error 
                let date = NSDate()
                reminder.title = "Do you have your bags?"
                let dueDateComponents = dateComponentFromNSDate(date.dateByAddingTimeInterval(Double(secondReminderStores) * 60.0))
                reminder.dueDateComponents = dueDateComponents
                reminder.calendar = self.eventStore.defaultCalendarForNewReminders()
                do {
                    try self.eventStore.saveReminder(reminder, commit: true)
                }catch{
                    print("Error creating and saving new reminder : \(error)")
                }

This line:

var eventStore: EKEventStore!

...creates the eventStore variable (property) and sets its type, but does not actually assign any EKEventStore instance value to it. Thus eventStore is nil , because that is the default value for any uninitialized Optional. You have shown no other code that ever assigned any EKEventStore instance value to it. Thus it is still nil when this line comes along:

let reminder = EKReminder(eventStore: self.eventStore)

...and so you crash. All perfectly nice and neat and logical.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM