作者:sumoly_ | 来源:互联网 | 2023-02-13 10:03
我正在尝试使用iOS 10的UserNotifications框架。
如果我不传递触发器,则通知的工作似乎很棒。他们会立即在应用程序中显示。但是我需要为触发传递一个延迟。谁能看到我代码中的漏洞?它应该使它延迟15秒,但它永远不会熄灭。
UNMutableNotificationContent* cOntent= [[UNMutableNotificationContent alloc] init];
content.title = [NSString localizedUserNotificationStringForKey:@"Hello!" arguments:nil];
content.body = [NSString localizedUserNotificationStringForKey:@"Hello_message_body"
arguments:nil];
content.sound = [UNNotificationSound defaultSound];
content.categoryIdentifier = @"WhatUpsw";
NSString *imageName = @"hug2";
NSURL *url = [[NSBundle mainBundle]URLForResource:imageName withExtension:@"jpg"];
UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:imageName URL:url options:nil error:nil];
content.attachments = @[attachment];
// Deliver the notification in five seconds.
UNTimeIntervalNotificationTrigger* trigger = [ UNTimeIntervalNotificationTrigger
triggerWithTimeInterval:15 repeats:NO];
UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecondsw"
content:content trigger:trigger];
// Schedule the notification.
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(@"Something went wrong: %@",error);
} else {
NSLog(@"All good!: %@", request);
}
}];
还检查未决的请求,我看到:
<__NSArrayM 0x17024d170>(
, hasDefaultAction: YES, defaultActionTitle: (null), shouldAddToNotificationsList: YES, shouldAlwaysAlertWhileAppIsForeground: NO, shouldLockDevice: NO, shouldPauseMedia: NO, isSnoozeable: NO, fromSnooze: NO, darwinNotificationName: (null), darwinSnoozedNotificationName: (null), trigger: >
)
Bill..
5
仅当您的应用程序在前台运行时,才会出现问题吗?如果在达到触发时间之前关闭应用程序或切换到另一个应用程序,则通知是否正常运行?
为了让应用程序运行时显示通知,您需要设置UNUserNotificationCenterDelegate
在appController(_:didFinishLaunching:)
:
func appController(_ appController: TVApplicationController, didFinishLaunching options: [String : Any]?) {
// ...
UNUserNotificationCenter.current().delegate = self
// ...
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
completionHandler(.alert)
}
需要在启动完成之前设置委托。
1> Bill..:
仅当您的应用程序在前台运行时,才会出现问题吗?如果在达到触发时间之前关闭应用程序或切换到另一个应用程序,则通知是否正常运行?
为了让应用程序运行时显示通知,您需要设置UNUserNotificationCenterDelegate
在appController(_:didFinishLaunching:)
:
func appController(_ appController: TVApplicationController, didFinishLaunching options: [String : Any]?) {
// ...
UNUserNotificationCenter.current().delegate = self
// ...
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
completionHandler(.alert)
}
需要在启动完成之前设置委托。