【问题标题】:iOS - How can I schedule something once a day?iOS - 我怎样才能安排一天一次的事情?
【发布时间】:2015-06-19 18:01:45
【问题描述】:

我知道有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重启后是否需要重新设置间隔?

【问题讨论】:

    标签: ios swift alarm


    【解决方案1】:

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

    1. 当您说“通知”时,您真的是指通知用户某事吗?

      在这种情况下,这里的替代方法是创建一个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. 或者您的意思是启动某些过程,例如从远程服务器获取数据。

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

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

    【讨论】:

    • 嗯,我想做的是介于两者之间:每天在同一时间向用户提问(例如:每天晚上 9 点询问用户是否吃药,然后用户必须回答:是/否)
    • 一定要查看本地通知流程。我想它会在你的小巷里。您可以对警报的性质有一定的灵活性,如果用户点击警报,您的应用程序将在前台打开,然后您可以做任何您想做的事情。
    • 太好了,这似乎是关键:notification.fireDate = ...; notification.repeatInterval = .CalendarUnitDay... 所以在 fireDate 中,如果我有“2015 年 6 月 19 日下午 6 点”,repeatInterval 将负责重复通知2015 年 6 月 20 日下午 6 点?
    • 是的,它就是这样工作的。试试看,你会看到的。尝试 NSDate().dateByAddingTimeInterval(30)(即从现在起 30 秒)为 fireDate.CalendarUnitMinuterepeatInterval。如果您随后点击“主页”按钮离开应用程序,您将看到具有该间隔的通知。 (如果应用程序仍在运行,您将不会看到警报,但会在您的应用程序委托上调用 didReceiveLocalNotification,您可以执行任何您想要的应用程序内进程。
    • 最后一个问题呢?:Will I need to set again the interval if the iPhone/iPad is rebooted?,在你回答之后,应该是:will i need to set again the notification after device reboot?
    猜你喜欢
    • 1970-01-01
    • 2010-10-21
    • 2011-01-16
    • 2021-02-26
    • 2020-04-06
    • 1970-01-01
    • 2020-05-24
    • 2017-08-30
    • 1970-01-01
    相关资源
    最近更新 更多