permission objective notification example ios uilocalnotification

objective - ¿Cómo puedo crear notificaciones locales en iOS?



swift local notification (6)

Aquí hay un código de muestra para LocalNotification que funcionó para mi proyecto.

C objetivo:

Este bloque de código en el archivo 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"); }

Este bloque de código en el archivo .m de cualquier ViewController :

-(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]; }

El código anterior muestra un AlertView después de un intervalo de tiempo de 7 segundos cuando se presiona el botón que vincula a startLocalNotification Si la aplicación está en segundo plano, muestra BadgeNumber como 10 y con sonido de notificación predeterminado.

Este código funciona bien para iOS 7.xy siguientes, pero para iOS 8 generará el siguiente error en la consola:

Intentar programar una notificación local con una alerta pero no haber recibido permiso del usuario para mostrar alertas

Esto significa que necesita registrarse para recibir notificaciones locales. Esto se puede lograr usando:

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

También puede recomendar un blog para notificaciones locales.

Rápido:

AppDelegate.swift archivo AppDelegate.swift debería verse así:

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 }

El archivo rápido (por ejemplo, ViewController.swift ) en el que desea crear una notificación local debe contener el siguiente código:

//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) . . . } . . . }

La forma en que utilizas para trabajar con notificaciones locales en iOS 9 y versiones posteriores es completamente diferente en iOS 10.

Debajo de la captura de pantalla de las notas de la versión de Apple se muestra esto.

Puede referir el documento de referencia de apple para UserNotification.

Debajo está el código para la notificación local:

C objetivo:

  1. En el archivo App-delegate.h use @import UserNotifications;

  2. El delegado de aplicaciones debe cumplir con el protocolo UNUserNotificationCenterDelegate

  3. En didFinishLaunchingOptions usa el siguiente código:

    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. Ahora crea un botón en cualquier controlador de vista y en IBAction usa el siguiente código:

    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. En el archivo AppDelegate.swift use import UserNotifications
  2. Appdelegate debe cumplir con el protocolo UNUserNotificationCenterDelegate
  3. En didFinishLaunchingWithOptions utilice el código siguiente

    // 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. Ahora crea un botón en cualquier controlador de vista y en IBAction usa el siguiente código:

    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)

Me gustaría saber cómo puedo configurar las notificaciones locales para que, en el momento en que configuro, mi aplicación genere una notificación / alerta con un mensaje personalizado ...


Crear notificaciones locales es bastante fácil. Solo sigue estos pasos.

  1. En la función viewDidLoad () pide permiso al usuario para que sus aplicaciones quieran mostrar notificaciones. Para esto podemos usar el siguiente código.

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in })

  2. Luego puede crear un botón, y luego en la función de acción puede escribir el siguiente código para mostrar una notificación.

    //creating the notification content let content = UNMutableNotificationContent() //adding title, subtitle, body and badge content.title = "Hey this is Simplified iOS" content.subtitle = "iOS Development is fun" content.body = "We are learning about iOS Local Notification" content.badge = 1 //getting the notification trigger //it will be called after 5 seconds let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) //getting the notification request let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger) //adding the notification to notification center UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

  3. Se mostrará la notificación, simplemente haga clic en el botón de inicio después de tocar el botón de notificación. Como cuando la aplicación está en primer plano, la notificación no se muestra. Pero si está utilizando iPhone X. Puede mostrar notificaciones incluso cuando la aplicación está en primer plano. Para esto, solo necesita agregar un delegado llamado UNUserNotificationCenterDelegate

Para obtener más detalles, visite esta publicación en el blog: Tutorial de notificación local de iOS


En el archivo appdelegate.m escriba el siguiente código en applicationDidEnterBackground para obtener la notificación local

- (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]]; }


Para usuarios de iOS 8 y superiores, incluye esto en el delegado de la aplicación para que funcione.

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

Y luego agregar estas líneas de código ayudaría,

- (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]]; }

Esto funciona, pero en iOS 8.0 y posterior , su aplicación debe registrarse para notificaciones de usuario utilizando -[UIApplication registerUserNotificationSettings:] antes de poder programar y presentar UILocalNotifications, no lo olvide.


-(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];