如何在iphone应用程序中创build本地通知

我想知道我(作为开发人员)如何设置本地通知,以便在我设置的时候,我的应用程序生成一个通知/提醒与定制的消息…

以下是LocalNotification的示例代码, 适用于我的项目。

Objective-C的:

这个代码块在AppDelegate文件中:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey]; // Override point for customization after application launch. return YES; } // This code block is invoked when application is in foreground (active-mode) -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { UIAlertView *notificationAlert = [[UIAlertView alloc] initWithTitle:@"Notification" message:@"This local notification" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; [notificationAlert show]; // NSLog(@"didReceiveLocalNotification"); } 

这个代码块在任何ViewController .m文件中:

 -(IBAction)startLocalNotification { // Bind this method to UIButton action NSLog(@"startLocalNotification"); UILocalNotification *notification = [[UILocalNotification alloc] init]; notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:7]; notification.alertBody = @"This is local notification!"; notification.timeZone = [NSTimeZone defaultTimeZone]; notification.soundName = UILocalNotificationDefaultSoundName; notification.applicationIconBadgeNumber = 10; [[UIApplication sharedApplication] scheduleLocalNotification:notification]; } 

上面的代码显示一个AlertView时间间隔为7秒后按下绑定startLocalNotificationbutton如果应用程序在后台,则显示BadgeNumber为10,并使用默认通知声音。

此代码适用于iOS 7.x及更低版本,但对于iOS 8,它将在控制台上提示以下错误

尝试使用警报安排本地通知,但尚未收到用户显示警报的权限

这意味着您需要注册本地通知。 这可以通过以下方式实现:

 if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){ [application registerUserNotificationSettings [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]]; } 

您也可以参考博客本地通知。

迅速:

你的AppDelegate.swift文件应该是这样的:

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert, categories: nil)) return true } 

您要在其中创build本地通知的swift文件(比如说ViewController.swift )应该包含以下代码:

 //MARK: - Button functions func buttonIsPressed(sender: UIButton) { println("buttonIsPressed function called \(UIButton.description())") var localNotification = UILocalNotification() localNotification.fireDate = NSDate(timeIntervalSinceNow: 3) localNotification.alertBody = "This is local notification from Swift 2.0" localNotification.timeZone = NSTimeZone.localTimeZone() localNotification.repeatInterval = NSCalendarUnit.CalendarUnitMinute localNotification.userInfo = ["Important":"Data"]; localNotification.soundName = UILocalNotificationDefaultSoundName localNotification.applicationIconBadgeNumber = 5 localNotification.category = "Message" UIApplication.sharedApplication().scheduleLocalNotification(localNotification) } //MARK: - viewDidLoad class ViewController: UIViewController { var objButton : UIButton! . . . override func viewDidLoad() { super.viewDidLoad() . . . objButton = UIButton.buttonWithType(.Custom) as? UIButton objButton.frame = CGRectMake(30, 100, 150, 40) objButton.setTitle("Click Me", forState: .Normal) objButton.setTitle("Button pressed", forState: .Highlighted) objButton.addTarget(self, action: "buttonIsPressed:", forControlEvents: .TouchDown) . . . } . . . } 

您在iOS 9及以下版本中使用“本地通知”的方式在iOS 10中完全不同。

从苹果发行说明屏幕抓取描述这一点。

截图

您可以参考AppleNotification的参考文档 。

以下是本地通知的代码:

Objective-C的:

  1. App-delegate.h文件中使用@import UserNotifications;

  2. 应用程序委托应符合UNUserNotificationCenterDelegate协议

  3. didFinishLaunchingOptions使用下面的代码:

     UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!error) { NSLog(@"request authorization succeeded!"); [self showAlert]; } }]; -(void)showAlert { UIAlertController *objAlertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"show an alert!" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { NSLog(@"Ok clicked!"); }]; [objAlertController addAction:cancelAction]; [[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:objAlertController animated:YES completion:^{ }]; } 
  4. 现在在任何视图控制器中创build一个button,在IBAction中使用下面的代码:

     UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init]; objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@“Notification!” arguments:nil]; objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@“This is local notification message!“arguments:nil]; objNotificationContent.sound = [UNNotificationSound defaultSound]; // 4. update application icon badge number objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1); // Deliver the notification in five seconds. UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10.f repeats:NO]; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@“ten” content:objNotificationContent trigger:trigger]; // 3. schedule localNotification UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { NSLog(@“Local Notification succeeded“); } else { NSLog(@“Local Notification failed“); } }]; 

Swift 3:

  1. AppDelegate.swift文件中使用import UserNotifications
  2. Appdelegate应符合UNUserNotificationCenterDelegate协议
  3. didFinishLaunchingWithOptions使用下面的代码

     // Override point for customization after application launch. let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in // Enable or disable features based on authorization. if error != nil { print("Request authorization failed!") } else { print("Request authorization succeeded!") self.showAlert() } } func showAlert() { let objAlert = UIAlertController(title: "Alert", message: "Request authorization succeeded", preferredStyle: UIAlertControllerStyle.alert) objAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) //self.presentViewController(objAlert, animated: true, completion: nil) UIApplication.shared().keyWindow?.rootViewController?.present(objAlert, animated: true, completion: nil) } 
  4. 现在在任何视图控制器中创build一个button,在IBAction中使用下面的代码:

     let content = UNMutableNotificationContent() content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil) content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil) content.sound = UNNotificationSound.default() content.categoryIdentifier = "notify-test" let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false) let request = UNNotificationRequest.init(identifier: "notify-test", content: content, trigger: trigger) let center = UNUserNotificationCenter.current() center.add(request) 

在appdelegate.m文件中,在applicationDidEnterBackground中写下以下代码以获取本地通知

 - (void)applicationDidEnterBackground:(UIApplication *)application { UILocalNotification *notification = [[UILocalNotification alloc]init]; notification.repeatInterval = NSDayCalendarUnit; [notification setAlertBody:@"Hello world"]; [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]]; [notification setTimeZone:[NSTimeZone defaultTimeZone]]; [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]]; } 
 - (void)applicationDidEnterBackground:(UIApplication *)application { UILocalNotification *notification = [[UILocalNotification alloc]init]; notification.repeatInterval = NSDayCalendarUnit; [notification setAlertBody:@"Hello world"]; [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]]; [notification setTimeZone:[NSTimeZone defaultTimeZone]]; [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]]; } 

这是行得通的, 但在iOS 8.0和更高版本中 ,您的应用程序必须先注册用户通知,然后才能够调度并呈现UILocalNotifications,请不要忘记这一点。

iOS 8用户及以上版本,请包括在应用程序委托,使其工作。

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) { [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]]; } return YES; } 

然后添加这行代码将有所帮助,

 - (void)applicationDidEnterBackground:(UIApplication *)application { UILocalNotification *notification = [[UILocalNotification alloc]init]; notification.repeatInterval = NSDayCalendarUnit; [notification setAlertBody:@"Hello world"]; [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]]; [notification setTimeZone:[NSTimeZone defaultTimeZone]]; [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]]; } 
 -(void)kundanselect { NSMutableArray *allControllers = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers]; NSArray *allControllersCopy = [allControllers copy]; if ([[allControllersCopy lastObject] isKindOfClass: [kundanViewController class]]) { [[NSNotificationCenter defaultCenter]postNotificationName:@"kundanViewControllerHide"object:nil userInfo:nil]; } else { [[NSUserDefaults standardUserDefaults] setInteger:4 forKey:@"selected"]; [self performSegueWithIdentifier:@"kundansegue" sender:self]; } } 

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ApparelsViewControllerHide) name:@"ApparelsViewControllerHide" object:nil];