且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Swift 2中安排特定时间的本地通知

更新时间:2023-01-06 08:31:34

准备显示本地通知需要两个主要步骤:

Preparing to show local notifications requires 2 main steps:

在iOS 8或更高版本上,您的应用必须询问并获得用户的权限才能显示本地通知.可以在您的AppDelegate中按以下步骤进行权限授予.

On iOS 8+ your app must ask and, subsequently, be granted permission by the user to display local notifications. Asking permission can be done as follows in your AppDelegate.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    ...
    if #available(iOS 8, *) {
        application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil))
    }

    return true
}

当您的应用程序在iOS 8之前的操作系统上运行时,请勿调用registerUserNotificationSettings(_:).否则,您的应用程序将在运行时崩溃.幸运的是,这不是问题,因为您使用的是Swift 2.

Do not call registerUserNotificationSettings(_:) when your app is running on a pre-iOS 8 operating system. Otherwise, your app will crash at runtime. Luckily, this shouldn't be a problem since you're working with Swift 2.

安排将来的通知fireDate.

let notification:UILocalNotification = UILocalNotification()
...
... // set the notification's category, alertAction, alertBody, etc.
...
notification.fireDate = ... // set to a future date
UIApplication.sharedApplication().scheduleLocalNotification(notification)

不幸的是,根据@aprogrmr的此堆栈溢出答案

Unfortunately, according to this Stack Overflow answer by @progrmr,

您不能使用 UILocalNotification .之前已经问过了(见下文),但是 仅提供有限的选项. 特定值.

You cannot set custom repeat intervals with UILocalNotification. This has been asked before (see below) but only limited options are provided. The repeatInterval parameter is an enum type and it limited to specific values.

您不能将这些枚举相乘并获得它们的倍数 间隔.您最多只能在64个本地通知中设置 您的应用.除非触发,否则您不能重新安排通知的时间,除非 用户在通知触发时选择运行您的应用(他们可能会 不运行它).

You cannot multiply those enumerations and get multiples of those intervals. You cannot have more than 64 local notifications set in your app. You cannot reschedule a notification once it fires unless the user chooses to run your app when the notification fires (they may not run it).

有重复间隔乘数的请求发布在此处. 您可以在其中添加评论.我建议提交错误报告或功能 向苹果请求(url?).

There is a request for repeat interval multipliers posted here. You can add comments to it. I suggest filing a bug report or feature request (url?) with Apple.

许多其他Stack Overflow答案也证实了以上引文中的声明.访问指向完整引用的答案的链接,其中包含支持的答案的列表.

Many other Stack Overflow answers confirm the claims in the quotes above. Visit the link to the full quoted answer, which contains a list of supporting answers.

您的情况可能的解决方法是安排3条本地通知.将每一个分别设置为分别在6:28 AM,12:28 PM和5:28 PM开火.然后,将所有3个本地通知的repeatInterval设置为.CalendarUnitWeekday.

A potential workaround for your case would be to schedule 3 local notifications. Set each one to fire at 6:28 AM, 12:28 PM, and 5:28 PM, respectively. Then, set the repeatInterval of all 3 local notifications to .CalendarUnitWeekday.