2011-05-18 33 views

Respuesta

50

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]]; 
} 
+0

Thx. Me ayudó: D – Vladimir

+9

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: –

72

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.

Screenshot

Se puede hacer referencia a apple reference document UserNotification.

A continuación se muestra el código para la notificación local:

Objective-C:

  1. En App-delegate.h archivo utilización @import UserNotifications;

  2. App-delegado debe ajustarse a UNUserNotificationCenterDelegate protocolo

  3. En 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:^{    
        }]; 
    
    } 
    
  4. 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:

  1. En AppDelegate.swift fil E Utilice import UserNotifications
  2. AppDelegate deben ajustarse a UNUserNotificationCenterDelegate protocolo
  3. 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) 
    } 
    
  4. 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) 
    
+1

¿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? –

+1

Además, ¿por qué su archivo AppDelegate.swift tiene didFinishLaunchingWithOptions dos veces? –

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

1
- (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.

+0

- [UIApplicationuserUserNotificationSettings:] anulará la configuración de notificación de inserción. así que tenga cuidado si utiliza la notificación push pushable. –

0

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

} 
1

Crear notificaciones locales son bastante fáciles. Solo sigue estos pasos.

  1. 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 
    }) 
    
  2. 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) 
    
  3. 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

+0

¿Es posible repetir la notificación todos los días con tiempo pacífico y repetir hasta que se abra la aplicación? –

Cuestiones relacionadas