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

标签 ios swift alarm

我知道有 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 所在的 View 也必须存在,即:无法关闭该 View (我说得对吗?)

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

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

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

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

那么,在 iOS 中,是否有类似 scheduledTimerWithInterval 的大间隔?

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

最佳答案

是的,要使用 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. 或者您的意思是启动某个过程,例如从远程服务器获取数据。

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

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

关于iOS - 我怎样才能安排一天一次的事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30944537/

相关文章:

ios - 如何在应用程序关闭时执行操作?

iphone - 构建成功但未在模拟器上运行

iphone - NSDate从字符串给出错误的结果

swift - Firebase SDK 3.x Linkedin 登录

ios - 如何在后台处理本地通知?

java - 从最近的应用程序中删除应用程序后的 Jobscheduler

ios - 如何从 parse.com 获取推送通知历史记录? (iOS)

ios - 发布 nsnotification 但观察者没有听到

ios - UIBezierPath roundedRect 有奇怪的间隙

ios - UISlider 设置值