2013-06-19 4 views
10

Alles, was ich bis jetzt gesehen habe, zeigt, dass ich eine Push-Benachrichtigung Alarm in meinem AppDelegate einrichten würde. Allerdings erfordert meine App, dass der Benutzer einen Registrierungsprozess durchläuft, und ich möchte den Benutzer nicht fragen, ob er Push-Benachrichtigungen erhalten möchte, es sei denn, der Benutzer ist unter der viewController angekommen, die erscheint, nachdem der Registrierungsprozess abgeschlossen ist.Registrierung für Remote-Benachrichtigungen außerhalb der App Delegate

Kann ich etwas von diesem Code in die viewDidLoad Methode eines View-Controllers anders als meine App Delegate? Muss ich diese beiden unteren Methoden "didRegisterForRemoteNotificationsWithDeviceToken" und "didReceiveRemoteNotification" in meinem App-Delegaten belassen oder sollte ich sie dorthin verschieben, wo ich versuche, mich für Remote-Benachrichtigungen zu registrieren?

Ich melde mich für Push-Benachrichtigungen in meiner app mit den Codeblöcken unter:

Im didFinishLaunchingWithOptions Methode meiner AppDelegate:

[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge| 
               UIRemoteNotificationTypeAlert| 
               UIRemoteNotificationTypeSound]; 

Methods in meinen app-Delegaten hinzugefügt:

- (void)application:(UIApplication *)application 
     didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 
{ 
    // Store the deviceToken 
} 

- (void)application:(UIApplication *)application 
     didReceiveRemoteNotification:(NSDictionary *)userInfo { 
    //handle push notification 
} 

Die Ressourcen, die ich besucht habe ich Geben Sie an, dass dieser Codeblock

Antwort

18

Sie können den Registrierungsanruf jederzeit ausführen - und es ist eine gute Idee, dies nur zu tun, wenn Sie in der App wissen, dass der Benutzer Push-Benachrichtigungen erhalten soll.

Die beiden Anwendungsdelegatenrückrufe müssen jedoch in Ihrem Anwendungsdelegaten enthalten sein, da Sie sich für Benachrichtigungstypen für den Anwendungsdelegaten registrieren, und Sie haben nur einen. Ich würde vorschlagen, eine Anwendung Delegate Methode zum Aufruf, dass dann die Registrierung macht, können Sie es von Ihrem View-Controller über [[UIApplication sharedApplication] delegate] aufrufen (das Ergebnis dieses Aufrufs zu Ihrer Anwendung Delegate-Klasse zu übertragen).

+0

Ein bisschen spät anrufen, aber dies akzeptiert werden sollte. – sudo

4

Die beste Methode ist, in AppDelegate Methode die remove Benachrichtigung zu handhaben, NSNotificationCenter

[[NSNotificationCenter defaultCenter] postNotification:@"remoteNotification" withObject:whateverYouWantHere]; 

dann die NSNotificationCenter verwenden mit einer Benachrichtigung auszusenden alle interessierten UIViewControllers als Beobachter für die remoteNotification Benachrichtigung hinzufügen .

11

Diese Antwort ist 'Antwort' von Kendall Helmstetter Gelner (Kendalls Antwort hat 0 Abstimmungs-Ups, aber es hat gut funktioniert, und ich habe nicht genug Punkte, um die Antwort abzustimmen). Folgende Kendall Anraten meiner Ansicht-Controller, CMRootViewController.m ->

#pragma mark - push notificaiton 
-(void)registerToReceivePushNotification { 
    // Register for push notifications 
    UIApplication* application =[UIApplication sharedApplication]; 
    [application registerForRemoteNotificationTypes: 
    UIRemoteNotificationTypeBadge | 
    UIRemoteNotificationTypeAlert | 
    UIRemoteNotificationTypeSound]; 
} 

und die beiden Anwendungs ​​Delegierten Rückrufe sind in meiner app-Delegaten, CMAppDelegate.m ->

// handle user accepted push notification, update parse 
- (void)application:(UIApplication *)application 
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)newDeviceToken { 
    // Store the deviceToken in the current installation and save it to Parse. 
    PFInstallation *currentInstallation = [PFInstallation currentInstallation]; 
    [currentInstallation setDeviceTokenFromData:newDeviceToken]; 

    // enable future push to deviceId 
    NSUUID *identifierForVendor = [[UIDevice currentDevice] identifierForVendor]; 
    NSString* deviceId = [identifierForVendor UUIDString]; 
    [currentInstallation setObject:deviceId forKey:@"deviceId"]; 

    [currentInstallation saveInBackground]; 
} 


// handle push notification arrives when app is open 
- (void)application:(UIApplication *)application 
didReceiveRemoteNotification:(NSDictionary *)userInfo { 
    [PFPush handlePush:userInfo]; 
} 

danke Kendall.

0

SWIFT 3 und höher

Um Push-Benachrichtigung von außerhalb AppDelegate

import UserNotifications 

class HomeViewController: UIViewController 
{ 
    override func viewDidLoad() { 
     super.viewDidLoad() 

     let application = UIApplication.shared 

     registerPushNotification(application) 
    } 



    func registerPushNotification(_ application: UIApplication){ 

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

       if granted { 
        print("Notification: Granted") 

       } else { 
        print("Notification: not granted") 

       } 
      } 

      application.registerForRemoteNotifications() 
     } 

} 



extension HomeViewController{ 

    // Called when APNs has assigned the device a unique token 
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { 
     // Convert token to string 
     let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)}) 

     // Print it to console 
     print("APNs device token: \(deviceTokenString)") 

     // Persist it in your backend in case it's new 
    } 

    // Called when APNs failed to register the device for push notifications 
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { 
     // Print the error to console (you should alert the user that registration failed) 
     print("APNs registration failed: \(error)") 
    } 

    // Push notification received 
    func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) { 
     // Print notification payload data 
     print("Push notification received: \(data)") 
    } 
} 
Verwandte Themen