2014-07-19 9 views
17

Sto creando un'app di elenco delle cose da fare a tempo in cui gli utenti possono avviare un timer da una notifica della schermata di blocco facendo scorrere per rivelare un pulsante di avvio. Questa è una nuova funzionalità mostrata in iOS 8 ma c'è poca documentazione che mostra come implementare questa funzione. Qualcuno può mostrare come vorrei impostare l'azione "start" e il blocco di codice che viene eseguito quando viene premuto? Se l'app fosse chiusa, questa funzionalità funzionerebbe ancora?Come implementare le notifiche interattive ios8

+0

Do qualche soluzione per la tua domanda? – RayofHope

+0

Guardando i video degli sviluppatori mi ha mostrato come implementare il codice di azione di notifica di base. Video davvero utile. Per allenare l'ora di fine del timer, ho utilizzato il tempo in cui l'utente ha interagito con la notifica di avvio e aggiunto la durata del timer e l'ho utilizzato per impostare la data di attivazione di una nuova notifica. –

+0

Fornire con esempio o collegamento git per implementare. Grazie – Meet

risposta

40

@Shubhendu grazie per il link. Per quelli di voi che non vogliono sedersi nel video, ecco un breve riepilogo di ciò che è necessario fare per includere le notifiche interattive nell'applicazione.

  • Definire tutte le azioni che l'utente può eseguire dalle notifiche dell'app. Queste azioni vengono create utilizzando la classe UIMutableUserNotificationAction.

    UIMutableUserNotificationAction *action = [[UIMutableUserNotificationAction alloc] init]; 
    action.identifier = @"ACTION_ID"; // The id passed when the user selects the action 
    action.title = NSLocalizedString(@"Title",nil); // The title displayed for the action 
    action.activationMode = UIUserNotificationActivationModeBackground; // Choose whether the application is launched in foreground when the action is clicked 
    action.destructive = NO; // If YES, then the action is red 
    action.authenticationRequired = NO; // Whether the user must authenticate to execute the action 
    
  • Posizionare queste azioni in categorie. Ogni categoria definisce un gruppo di azioni che un utente può eseguire da una notifica. Queste categorie vengono create utilizzando UIMutableUserNotificationCategory.

    UIMutableUserNotificationCategory *category = [[UIMutableUserNotificationCategory alloc] init]; 
    category.identifier = @"CATEGORY_ID"; // Identifier passed in the payload 
    [category setActions:@[action] forContext:UIUserNotificationActionContextDefault]; // The context determines the number of actions presented (see documentation) 
    
  • Registrare le categorie nelle impostazioni. Si noti che la registrazione delle categorie non sostituisce chiedere il permesso all'utente di inviare notifiche a distanza, utilizzando [[UIApplication sharedApplication] registerForRemoteNotifications]

    NSSet *categories = [NSSet setWithObjects:category, nil]; 
    NSUInteger types = UIUserNotificationTypeNone; // Add badge, sound, or alerts here 
    UIUserNotificationSettings *settings = [UIUSerNotificationSettings settingsForTypes:types categories:categories]; 
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; 
    
  • Invia l'identificativo della categoria nel payload di notifica.

    { 
        "aps":{ 
         "alert":"Here's a notification", 
         ... 
         "category":"CATEGORY_ID" 
        } 
    } 
    
  • azioni dell'utente maniglia del delegato app implementando i metodi del protocollo UIApplicationDelegate: application:handleActionWithIdentifier:forRemoteNotification:completionHandler: per notifiche remote application:handleActionWithIdentifier:forLocalNotification:completionHandler: per le notifiche locali

+0

Grazie mille per la descrizione del carico utile della notifica! –

+0

questa dovrebbe essere la risposta accettata –

+0

È possibile avere 3 azioni di notifica interattiva? –

8

FASE 1:

NSString * const NotificationCategoryIdent = @"ACTIONABLE"; 
NSString * const NotificationActionOneIdent = @"ACTION_ONE"; 
NSString * const NotificationActionTwoIdent = @"ACTION_TWO"; 

- (void)registerForNotification { 

    UIMutableUserNotificationAction *action1; 
    action1 = [[UIMutableUserNotificationAction alloc] init]; 
    [action1 setActivationMode:UIUserNotificationActivationModeBackground]; 
    [action1 setTitle:@"Action 1"]; 
    [action1 setIdentifier:NotificationActionOneIdent]; 
    [action1 setDestructive:NO]; 
    [action1 setAuthenticationRequired:NO]; 

    UIMutableUserNotificationAction *action2; 
    action2 = [[UIMutableUserNotificationAction alloc] init]; 
    [action2 setActivationMode:UIUserNotificationActivationModeBackground]; 
    [action2 setTitle:@"Action 2"]; 
    [action2 setIdentifier:NotificationActionTwoIdent]; 
    [action2 setDestructive:NO]; 
    [action2 setAuthenticationRequired:NO]; 

    UIMutableUserNotificationCategory *actionCategory; 
    actionCategory = [[UIMutableUserNotificationCategory alloc] init]; 
    [actionCategory setIdentifier:NotificationCategoryIdent]; 
    [actionCategory setActions:@[action1, action2] 
        forContext:UIUserNotificationActionContextDefault]; 

    NSSet *categories = [NSSet setWithObject:actionCategory]; 
    UIUserNotificationType types = (UIUserNotificationTypeAlert| 
            UIUserNotificationTypeSound| 
            UIUserNotificationTypeBadge); 

    UIUserNotificationSettings *settings; 
    settings = [UIUserNotificationSettings settingsForTypes:types 
               categories:categories]; 

    [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; 
} 

PASSO 2: Per inviare questo tipo di notifica è sufficiente aggiungere la categoria al payload.

{ 
    "aps" : { 
     "alert" : "Pull down to interact.", 
     "category" : "ACTIONABLE" 
    } 
} 

FASE 3: Utilizzare questo metodo

application:handleActionWithIdentifier:forRemoteNotification:completionHand 
ler: 

[application:handleActionWithIdentifier:forLocalNotification:completionHandler: 
-> For LOCAL Notification] 

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler { 

    if ([identifier isEqualToString:NotificationActionOneIdent]) { 

     NSLog(@"You chose action 1."); 
    } 
    else if ([identifier isEqualToString:NotificationActionTwoIdent]) { 

     NSLog(@"You chose action 2."); 
    }  
    if (completionHandler) { 

     completionHandler(); 
    } 
} 

1.Refer link: Obj C tutorial

2. Swift Code Tutorial here

+0

Grazie @ramdy –

+0

Tutto questo è deprecato. – joan

2

Con iOS 8 è venuto un nuovo ed entusiasmante API per la creazione di notifiche interattive .Questi ti consentono di fornire funzionalità aggiuntive agli utenti al di fuori della tua applicazione.

Iniziamo. Ci sono 3 nuove classi in iOS 8 che sono necessarie: UIUserNotificationSettings, UIUserNotificationCategory, UIUserNotificationAction e le loro controparti mutabili.

Invece di limitarsi a registrarsi per i tipi di notifica (suoni, banner, avvisi) ora è possibile anche registrarsi per categorie e azioni di notifica personalizzate. Le categorie descrivono un tipo personalizzato di notifica che l'applicazione invia e contiene azioni che un utente può eseguire in risposta. Ad esempio ricevi una notifica che qualcuno ti ha seguito su un social network. In risposta potresti voler seguirli o ignorarli.

NSString * const NotificationCategoryIdent = @"ACTIONABLE"; 
NSString * const NotificationActionOneIdent = @"ACTION_ONE"; 
NSString * const NotificationActionTwoIdent = @"ACTION_TWO"; 

- (void)registerForNotification { 

    UIMutableUserNotificationAction *action1; 
    action1 = [[UIMutableUserNotificationAction alloc] init]; 
    [action1 setActivationMode:UIUserNotificationActivationModeBackground]; 
    [action1 setTitle:@"Action 1"]; 
    [action1 setIdentifier:NotificationActionOneIdent]; 
    [action1 setDestructive:NO]; 
    [action1 setAuthenticationRequired:NO]; 

    UIMutableUserNotificationAction *action2; 
    action2 = [[UIMutableUserNotificationAction alloc] init]; 
    [action2 setActivationMode:UIUserNotificationActivationModeBackground]; 
    [action2 setTitle:@"Action 2"]; 
    [action2 setIdentifier:NotificationActionTwoIdent]; 
    [action2 setDestructive:NO]; 
    [action2 setAuthenticationRequired:NO]; 

    UIMutableUserNotificationCategory *actionCategory; 
    actionCategory = [[UIMutableUserNotificationCategory alloc] init]; 
    [actionCategory setIdentifier:NotificationCategoryIdent]; 
    [actionCategory setActions:@[action1, action2] 
        forContext:UIUserNotificationActionContextDefault]; 

    NSSet *categories = [NSSet setWithObject:actionCategory]; 
    UIUserNotificationType types = (UIUserNotificationTypeAlert| 
            UIUserNotificationTypeSound| 
            UIUserNotificationTypeBadge); 

    UIUserNotificationSettings *settings; 
    settings = [UIUserNotificationSettings settingsForTypes:types 
               categories:categories]; 

    [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; 
} 

// JSON payload:

{ 
"aps" : { 
    "alert" : "Pull down to interact.", 
    "category" : "ACTIONABLE" 
    } 
} 

Ora per gestire le azioni selezionata dall'utente, ci sono 2 nuovi metodi sul protocollo UIApplicationDelegate: \

application:handleActionWithIdentifier:forLocalNotification:completionHandler: 
application:handleActionWithIdentifier:forRemoteNotification:completionHandler: 

Questi metodi otterrà chiamato, in background, quando l'utente seleziona un'azione dalla notifica push.

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler { 

    if ([identifier isEqualToString:NotificationActionOneIdent]) { 

     NSLog(@"You chose action 1."); 
    } 
    else if ([identifier isEqualToString:NotificationActionTwoIdent]) { 

     NSLog(@"You chose action 2."); 
    }  
    if (completionHandler) { 

     completionHandler(); 
    } 
} 
+0

Tutorial completo qui: https://nrj.io/simple-interactive-notifications-in-ios-8/ – nrj

2

Per ios10 uso spinta Actionable questo

UNAuthorizationOptions authOptions = 
UNAuthorizationOptionAlert 
| UNAuthorizationOptionSound 
    | UNAuthorizationOptionBadge; 
    [[UNUserNotificationCenter currentNotificationCenter] 
    requestAuthorizationWithOptions:authOptions 
    completionHandler:^(BOOL granted, NSError * _Nullable error) { 
    } 
    ]; 
UNNotificationAction *ok = [UNNotificationAction actionWithIdentifier:@"OK" 
                      title:NSLocalizedString(@"OK", nil) 
                     options:UNNotificationActionOptionForeground]; 
    UNNotificationAction *cancel = [UNNotificationAction actionWithIdentifier:@"CANCEL" 
                       title:NSLocalizedString(@"CANCEL", nil) 
                      options:UNNotificationActionOptionForeground]; 
    NSArray *buttons = @[ ok, cancel ]; 

    // create a category for message failed 
    UNNotificationCategory *buttonsAction = [UNNotificationCategory categoryWithIdentifier:@"ACTION_BUTTON" 
                        actions:buttons 
                      intentIdentifiers:@[] 
                        options:UNNotificationCategoryOptionCustomDismissAction]; 
NSSet *categories = [NSSet setWithObjects:buttonsAction, nil]; 

    // registration 
    [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:categories]; 
Problemi correlati