我正在制作一个包含 Today Extension 的应用。今天的扩展程序显示一个计时器列表,如果用户选择其中一个计时器,我想为该计时器创建并安排一个本地通知。
我的问题是通知的调度是用这行代码完成的:
UIApplication.sharedApplication().scheduleLocalNotification(notification)
非常不幸的是,它依赖于无法从扩展程序访问的 UIApplication.sharedApplication()
。
所以我的问题是:如何在 Today 扩展中安排本地通知?
有趣的是,我可以使用我的应用程序和我的扩展之间共享的代码创建一个框架,并且在该框架中我可以调用:
func schedule() {
// ...
let settings = UIUserNotificationSettings(forTypes: .Sound | .Alert, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
// ...
UIApplication.sharedApplication().scheduleLocalNotification(notification)
// ...
}
如果我随后从我的扩展中导入该框架并调用 schedule()
,我将得到以下输出:
Failed to inherit CoreMedia permissions from 13636: (null)
Attempting to schedule a local notification <UIConcreteLocalNotification: 0x7feaf3657a00>{fire date = Saturday, November 1, 2014 at 1:01:48 PM Western European Standard Time, time zone = (null), repeat interval = 0, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = Saturday, November 1, 2014 at 1:01:48 PM Western European Standard Time, user info = (null)} with an alert but haven't received permission from the user to display alerts
Attempting to schedule a local notification <UIConcreteLocalNotification: 0x7feaf3657a00>{fire date = Saturday, November 1, 2014 at 1:01:48 PM Western European Standard Time, time zone = (null), repeat interval = 0, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = Saturday, November 1, 2014 at 1:01:48 PM Western European Standard Time, user info = (null)} with a sound but haven't received permission from the user to play sounds
因此,在扩展中运行的模块可以访问 UIApplication.sharedApplication()
,因为此代码实际上尝试安排通知,但系统未准备好请求显示警报权限的扩展所以它失败了(无论如何看起来就是这样)。
我该如何解决这个问题?
另外,我知道我可以使用 url 启动我的应用程序并正常安排来自该应用程序的通知,但这不是用户友好的。拥有今天扩展的全部目的是让用户不必打开应用程序来安排通知。交互必须快速、简单和透明,将用户从他们正在使用的应用程序中拉出来只是为了运行几行代码然后完成它不是我想要的做事方式。
最佳答案
如果有人遇到这个问题,现在可以在 iOS 10 中实现,它是新的 UserNotifications 框架。要从您的应用程序扩展程序安排本地通知,您只需在您的扩展程序中调用这行代码:
UNUserNotificationCenter.current().add(<#UNNotificationRequest#>)
关于ios - 在 Today 扩展中安排本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26689629/