iOS - 我怎样才能安排一天一次的事情?

iOS - How can I schedule something once a day?

我知道有NSTimer.scheduledTimerWithInterval

这样使用的:

override func viewDidLoad() {
    super.viewDidLoad()

    var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}

func update() {
    // Something cool
}

但我假设 var timer 所在的视图也必须存在,即:无法关闭该视图(我说得对吗?)

如何在 iOS 中安排一天一次的事情,例如:每天晚上 8 点发送通知?

Android 中,我通过以下方式实现了这一点:

  1. 我使用了一个叫做 AlarmManager 的东西,它类似于 iOS scheduledTimerWithInterval 但是 大间隔 ,这是后台服务中的 运行。

  2. 在启动(引导)时,有另一个后台服务再次设置警报。这涵盖了 Android 设备关闭的情况(因此后台服务也被关闭)

所以,在 iOS 中,是否有类似 scheduledTimerWithInterval 的大间隔?

iPhone/iPad重启后是否需要重新设置间隔?

是的,要使用 NSTimer,应用程序必须 运行 在前台或后台运行。但是 Apple 非常特别,只允许某些类型的应用程序在后台继续 运行(以确保我们不会让应用程序随机 运行 以自己的特权运行并耗尽我们的电池在这个过程中 and/or 影响了我们在使用设备时的性能)。

  1. 当您说 "notification" 时,您的意思是要通知用户某事吗?

    在这种情况下,这里的替代方法是创建一个 UILocalNotification,这是一个用户通知(假设他们已经授予您的应用程序执行通知的权限),即使您的应用程序没有运行宁.

    例如,要注册本地通知:

    let application = UIApplication.sharedApplication()
    let notificationTypes: UIUserNotificationType = .Badge | .Sound | .Alert
    let notificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
    application.registerUserNotificationSettings(notificationSettings)
    

    然后安排重复通知:

    let notification = UILocalNotification()
    notification.fireDate = ...
    notification.alertTitle = ...
    notification.alertBody = ...
    notification.repeatInterval = .CalendarUnitDay
    application.scheduleLocalNotification(notification)
    

    有关详细信息,请参阅 Local and Remote Notification Programming Guide

  2. 或者你的意思是启动一些进程,比如从远程服务器获取数据。

    如果您希望应用在未 运行ning 的情况下也能获取数据,您可以使用后台获取。请参阅 iOS 的 应用程序编程指南中的 Fetching Small Amounts of Content Opportunistically

    请注意,使用后台提取时,您无需指定何时检索数据,而是系统会在自己选择的时间检查数据。据报道,它考虑的因素包括用户使用应用程序的频率、请求查看是否有数据的频率是否会导致实际上有新数据要检索等。您无法直接控制这些后台获取的时间。