23

Modifica: Quindi mettere l'app in background ha funzionato.Aggiungi notifica locale in ios10 - swift 3

originale:

Così ho cercato di aggiungere una notifica al nuovo UNUserNotificationCenter, ma non mi sembra di farlo.

mio controller della vista ha un'azione:

@IBAction func sendPressed(_ sender: AnyObject) { 
    let content = UNMutableNotificationContent() 

    content.title = "Hello" 
    content.body = "What up?" 
    content.sound = UNNotificationSound.default() 

    // Deliver the notification in five seconds. 
    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false) 
    let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger) 

    // Schedule the notification. 
    let center = UNUserNotificationCenter.current() 
    center.add(request) { (error) in 
     print(error) 
    } 
    print("should have been added") 
} 

override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 

    let center = UNUserNotificationCenter.current() 
    center.requestAuthorization([.alert, .sound]) { (granted, error) in 
    } 
} 

e ho un Notification Content Extension nel progetto pure, ma non sembra essere attivato a tutti, tutte le idee che cosa mi manca? Sto provando l'esempio dalla documentazione dell'utente, ma non mi sta dicendo altro o l'ho perso.

Qui: https://developer.apple.com/reference/usernotifications/unmutablenotificationcontent

anche: https://developer.apple.com/reference/usernotificationsui https://developer.apple.com/reference/usernotifications

+0

è possibile fare riferimento questo link per l'uso dettagliate http://jayprakashdubey.blogspot.in/2016/07/local- notification-in-ios-10-for_31.html –

+0

come impostare diversi componenti della data o come richiamare le notazioni locali più volte? – ArgaPK

risposta

28

È necessario registrarsi per la notifica ... ho provato e funziona.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
     // Override point for customization after application launch. 
     let center = UNUserNotificationCenter.current() 
     center.requestAuthorization([.alert, .sound]) { (granted, error) in 
      // Enable or disable features based on authorization. 
     } 
     return true 
    } 

Edit: Non avete bisogno di mettere la vostra applicazione in background per presentare la notifica da iOS 10 in poi.

Utilizzare la richiamata di seguito per configurare la notifica da presentare in primo piano.

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 

Here è un progetto di esempio.

+0

Sì, ho ancora questa fortuna. Hai un esempio completo dell'app, quindi posso vedere se mi sono perso qualcosa? – Bjarte

+0

per favore vedi la risposta aggiornata ... –

+0

ahhh, averlo in background ha fatto il trucco! – Bjarte

17

con Objective-C implemation:

Ho scritto un progetto demo qui: iOS10AdaptationTips.

  1. UserNotifications importazione

    ///Notification become independent from Foundation 
    @import UserNotifications; 
    
  2. autorizzazione richiesta di localNotification

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; 
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) 
             completionHandler:^(BOOL granted, NSError * _Nullable error) { 
              if (!error) { 
               NSLog(@"request authorization succeeded!"); 
               [self showAlert]; 
              } 
             }]; 
    

    richiesta di autorizzazione: enter image description here

  3. programma localNotification

  4. applicazione di aggiornamento numero icona distintivo

    //  //Deliver the notification at 08:30 everyday 
        //  NSDateComponents *dateComponents = [[NSDateComponents alloc] init]; 
        //  dateComponents.hour = 8; 
        //  dateComponents.minute = 30; 
        //  UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateComponents repeats:YES]; 
    
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; 
        content.title = [NSString localizedUserNotificationStringForKey:@"Elon said:" arguments:nil]; 
        content.body = [NSString localizedUserNotificationStringForKey:@"Hello Tom!Get up, let's play with Jerry!" 
                     arguments:nil]; 
        content.sound = [UNNotificationSound defaultSound]; 
    
        /// 4. update application icon badge number 
        content.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1); 
        // Deliver the notification in five seconds. 
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger 
                    triggerWithTimeInterval:5.f repeats:NO]; 
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond" 
                          content:content trigger:trigger]; 
        /// 3. schedule localNotification 
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; 
        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { 
         if (!error) { 
          NSLog(@"add NotificationRequest succeeded!"); 
         } 
        }]; 
    

allora apparirà in questo modo:

In Background: enter image description here Blocco schermo:
enter image description here

Se Repeat by l'impostazione predefinita mostra solo uno enter image description here invece di mostrare molti sulla schermata di blocco su iOS9: http://i67.tinypic.com/98t75s.jpg e anche supporto touch 3D automaticamente http://a67.tinypic.com/dorw3b.jpg

scrivo una demo qui: iOS10AdaptationTips.

+0

Ciao, ho eseguito la demo ma mi dà un'eccezione ** Assertion failure in - [UNTimeIntervalNotificationTrigger _initWithTimeInterval: ripetizioni:] ** durante l'esecuzione di ** UNTimeIntervalNotificationTrigger * trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval: 5.f ripete: YES]; ** . –

+1

Perché stai scrivendo in Objective-C? – 4thSpace

+9

Perché può;) – CMash

0

ho risolto il mio problema come segue (Firebase, Swift 3):

Trova questo metodo sul tuo AppDelegate:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 

Trova questa riga:

completionHandler() 

Fine insieme:

completionHandler([.alert,.sound,.badge]) 

notifiche non stanno sparando se non si passa le opzioni di presentazione per il metodo completionHandler.

+0

Non vedere il punto di un enorme quadro per fare qualcosa di così semplice. – Bjarte

+0

di Apple o Firebase? –

+0

Questo dovrebbe essere davvero usato senza un framework. È molto semplice da fare –