如何在背景中的特定日期时间在swift中运行任务,无论应用程序是打开还是关闭

我正在处理报警应用程序,我需要在特定时间安排报警,我使用scheduleLocalNotification来安排报警,它正常工作,如我所愿。 但是我需要在触发警报之前运行到我的API服务器的请求。 在该请求中,我想检查从API服务器返回的一些参数,如果满足某些条件。

如果任何人有一个在特定日期运行的方法 – swift的时间请帮助我

  func addAlarm (newAlarm: Alarm) { // Create persistent dictionary of data var alarmDictionary = NSUserDefaults.standardUserDefaults().dictionaryForKey(ALARMS_KEY) ?? Dictionary() // Copy alarm object into persistent data alarmDictionary[newAlarm.UUID] = newAlarm.toDictionary() // Save or overwrite data NSUserDefaults.standardUserDefaults().setObject(alarmDictionary, forKey: ALARMS_KEY) scheduleNotification(newAlarm, category: "ALARM_CATEGORY") scheduleNotification(newAlarm, category: "FOLLOWUP_CATEGORY") } /* NOTIFICATION FUNCTIONS */ func scheduleNotification (alarm: Alarm, category: String) { let notification = UILocalNotification() notification.category = category notification.repeatInterval = NSCalendarUnit.Day switch category { case "ALARM_CATEGORY": notification.userInfo = ["UUID": alarm.UUID] notification.alertBody = "Time to wake up!" notification.fireDate = alarm.wakeup notification.timeZone = NSTimeZone.localTimeZone() notification.soundName = "loud_alarm.caf" break case "FOLLOWUP_CATEGORY": notification.userInfo = ["UUID": alarm.followupID] notification.alertBody = "Did you arrive yet?" notification.fireDate = alarm.arrival notification.timeZone = NSTimeZone.localTimeZone() notification.soundName = UILocalNotificationDefaultSoundName break default: print("ERROR SCHEDULING NOTIFICATION") return } print("Notification=\(notification)") // For debugging purposes if alarm.isActive { UIApplication.sharedApplication().scheduleLocalNotification(notification) } } 

无法通过本地通知唤醒应用程序,这仅适用于远程通知。 根据通知编程指南 :

远程通知到达时,系统会在应用程序处于后台时正常处理用户交互。 它还向应用程序提供通知负载:didReceiveRemoteNotification:fetchCompletionHandler:iOS和tvOS中app委托的方法

但仍有一个问题; 即便如此,根据didReceiveRemoteNotification:fetchCompletionHandler: 文档 :不保证应用程序将被启动。

但是, 如果用户强行退出 ,系统不会自动启动您的应用程序。 在这种情况下,用户必须重新启动应用程序或重新启动设备,然后系统才会再次尝试自动启动应用程序。

我不认为有一种保证的方法可以在稍后的某个时刻安排块执行,而与当时应用程序的状态无关。 根据您的具体要求和频率,您可以注册fetch后台模式并实现application:performFetchWithCompletionHandler: 机会性地获取和validation服务器数据 。 最后一点:确保您是一个负责任的后台应用程序(根据我的经验,Apple认真对待此要求)