简体   繁体   English

在iOS应用程序的后台设置提醒

[英]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. 但是,当应用程序在后台运行时,当我调用相同的代码时,会出现致命错误:在展开Optional值时意外发现nil。 The code below is being called in the AppDelegate. 下面的代码在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. ...创建eventStore变量(属性)并设置其类型,但实际上并未为其分配任何EKEventStore实例值。 Thus eventStore is nil , because that is the default value for any uninitialized Optional. 因此eventStorenil ,因为这是任何未初始化的Optional的默认值。 You have shown no other code that ever assigned any EKEventStore instance value to it. 您没有显示其他代码向其分配任何EKEventStore实例值。 Thus it is still nil when this line comes along: 因此,当此行出现时,它仍然 nil

let reminder = EKReminder(eventStore: self.eventStore)

...and so you crash. ...于是你崩溃了。 All perfectly nice and neat and logical. 一切都非常好,整洁和合乎逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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