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

Pus*_*dra 5 iphone background-process ios uilocalnotification 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

spa*_*sas 2

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

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

但仍然有一个问题;即使如此,也不能保证该应用程序将会启动,因为根据didReceiveRemoteNotification:fetchCompletionHandler: 文档

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

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