Me gustaría saber cómo yo (como desarrollador) 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 ...cómo crear notificaciones locales en la aplicación iphone
Respuesta
en appdelegate.m archivo escribir el código follwing en applicationDidEnterBackground para obtener la notificación local de
- (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]];
}
Aquí es código de ejemplo para LocalNotification que trabajó para mi proyecto.
Objective-C:
Este bloque de código en el archivo de 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];
}
La pantalla el código de un AlertView después del intervalo de tiempo de 7 segundos cuando se presiona el botón que une 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.x y por debajo, pero para iOS 8 se le pedirá error siguiente en la consola:
El intento de programar una notificación local con una alerta, pero no han recibido el permiso del usuario para mostrar alertas
Esto significa que necesita registrarse para la notificación local. Esto se puede lograr usando:
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
También puede hacer referencia blog para la notificación local.
Swift:
Usted AppDelegate.swift
archivo debe tener este aspecto:
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 la notificación local debe contener por debajo de 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 de usar para trabajar con La notificación local en iOS 9 y siguientes es completamente diferente en iOS 10.
La captura de pantalla debajo de las notas del lanzamiento de Apple muestra esto.
Se puede hacer referencia a apple reference document UserNotification.
A continuación se muestra el código para la notificación local:
Objective-C:
En
App-delegate.h
archivo utilización@import UserNotifications;
App-delegado debe ajustarse a
UNUserNotificationCenterDelegate
protocoloEn
didFinishLaunchingOptions
uso por debajo de 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:^{ }]; }
Ahora crear un botón en cualquier controlador de vista y en IBAction utilizar por debajo de 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:
- En
AppDelegate.swift
fil E Utiliceimport UserNotifications
- AppDelegate deben ajustarse a
UNUserNotificationCenterDelegate
protocolo En
didFinishLaunchingWithOptions
uso por debajo de código// 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) }
Ahora crear un botón en cualquier controlador de vista y en IBAction utilizar por debajo de 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)
¿Necesito necesariamente ejecutar funcButtonIsPressed en un presione el botón? ¿Qué sucede si quiero que la aplicación, por defecto, proporcione esa notificación semanalmente, debería agregarla al viewDidLoad del VC inicial? –
Además, ¿por qué su archivo AppDelegate.swift tiene didFinishLaunchingWithOptions dos veces? –
-(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];
- (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 se trabaja, pero en iOS 8.0 y posterior, la aplicación debe registrar las notificaciones de usuario utilizando -[UIApplication registerUserNotificationSettings:]
antes de poder programar y presentar UILocalNotifications, no se olvide esto.
- [UIApplicationuserUserNotificationSettings:] anulará la configuración de notificación de inserción. así que tenga cuidado si utiliza la notificación push pushable. –
iOS 8 o superior, inclúyalo en el delegado de aplicaciones 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 a continuación, añadir 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]];
}
Crear notificaciones locales son bastante fáciles. Solo sigue estos pasos.
En la función viewDidLoad(), solicite permiso al usuario para que sus aplicaciones muestren las notificaciones. Para esto podemos usar el siguiente código.
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in })
continuación, puede crear un botón, y luego en la función de acción que puede escribir el siguiente código para mostrar una notificación. Se mostrará
//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)
notificación, basta con hacer clic en el botón de inicio después de pulsar 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 ello sólo tiene que añadir un delegado pidió UNUserNotificationCenterDelegate
Para más detalles visite esta entrada del blog: iOS Local Notification Tutorial
¿Es posible repetir la notificación todos los días con tiempo pacífico y repetir hasta que se abra la aplicación? –
- 1. iPhone: notificaciones locales diarias
- 2. Alarma de iPhone usando notificaciones locales repetidas
- 3. ¿Es posible mostrar notificaciones locales mientras la aplicación iphone está en pantalla?
- 4. Borrar insignia de aplicación con notificaciones locales
- 5. Envío de notificaciones locales en Android
- 6. ¿Cómo configurar notificaciones locales en Mac OS X?
- 7. iphone y notificaciones: ¿número máximo de notificaciones?
- 8. Registrar la aplicación iPhone para notificaciones push no funciona
- 9. Cómo agregar notificaciones al icono en la aplicación iOS
- 10. ¿Reproduce el sonido predeterminado de notificaciones locales al mostrar UIAlertView?
- 11. notificaciones de iPhone Notify_post
- 12. ¿Cómo crear un gráfico de líneas en la aplicación iphone?
- 13. Cómo crear un UIAlertView personalizado en la aplicación para iphone
- 14. notificaciones push múltiples en 1 dispositivo - iPhone
- 15. ejabberd mod_offline iphone notificaciones push
- 16. ¿Cómo implementa la aplicación Facebook iPhone la ventana emergente para notificaciones?
- 17. ¿Cómo recibir notificaciones de Facebook en iPhone SDK?
- 18. ¿Cómo hacer notificaciones en android?
- 19. Cómo recibir UIAccessibilityNotifications en la aplicación de iPhone
- 20. cómo crear el binario de la aplicación iphone
- 21. Datos principales: observe los cambios y registre las notificaciones locales
- 22. ¿Cuál es una buena forma de administrar las notificaciones locales que ha programado su aplicación?
- 23. iPhone: ¿crear rutas de Quartz en la aplicación vectorial?
- 24. enviar notificaciones push a iphone desde python
- 25. notificaciones Push para Android y iPhone
- 26. iOS aplicación: ¿cómo borrar las notificaciones?
- 27. Crear una aplicación para iPhone sin Xcode
- 28. Cómo incrustar iPhone-Wax en la aplicación
- 29. ¿Cómo usar FLAC en la aplicación iPhone?
- 30. Cómo configurar CMake para crear una aplicación para el iPhone
Thx. Me ayudó: D – Vladimir
Cuando programa solo UNA notificación usando setScheduledLocalNotifications: es innecesario. Hay método scheduleLocalNotification que toma un argumento: la notificación debe programarse. https://developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/UIApplication_Class/index.html#//apple_ref/occ/instm/UIApplication/scheduleLocalNotification: –