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

标签 ios swift locationmanager ekeventstore

我正在尝试在用户进入某个区域时创建提醒。该代码用于在应用程序打开时创建提醒。但是,当我在应用程序位于后台时调用相同的代码时,我收到 fatal error :在展开可选值时意外发现 nil。下面的代码在 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)")
                }

最佳答案

这一行:

var eventStore: EKEventStore!

...创建 eventStore 变量(属性)并设置其类型,但实际上并未为其分配任何 EKEventStore 实例值。因此,eventStorenil,因为这是任何未初始化的Optional 的默认值。您没有显示任何向其分配任何 EKEventStore 实例值的其他代码。因此,当出现这一行时,它是仍然 nil:

let reminder = EKReminder(eventStore: self.eventStore)

...然后你就崩溃了。一切都完美、整洁、合乎逻辑。

关于ios - 在 iOS 应用程序的后台设置提醒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35387102/

相关文章:

ios - AHEasing 是否在 Swift 中运行?

ios - iPhone : How to play a YouTube video in a certain view (instead of fullscreen)

android - 通过网络请求位置更新时出现问题

iphone - 从 viewController 的 viewDidAppear 方法调用 location

java - Android LocationManager 获取坐标的整数值(而 double 值)

ios - UITapGestureRecognizer 不工作 - Swift 3

ios - 在 MKMapView 上放置一个图钉

Swift - 标题 UICollectionViewController 动态高度

ios - 更新后的plist数据

ios - 用户界面 ImageView : add tap event from Interface Builder