在app delegate之外注册远程通知

时间:2013-06-19 04:26:05

标签: iphone ios objective-c push-notification

到目前为止我看到的所有内容都表明我会在AppDelegate中设置推送通知提醒。但是,我的应用程序要求用户完成注册过程,我不想询问用户是否希望接收推送通知,除非用户已到达注册过程后出现的viewController完整。

我是否可以将某些代码放在除我的应用代理之外的视图控制器的viewDidLoad方法中?我是否需要将这两个底层方法“didRegisterForRemoteNotificationsWithDeviceToken”和“didReceiveRemoteNotification”留在我的应用代理中,还是应该将它们移到我尝试注册远程通知的任何地方?

我正在我的应用中使用以下代码块注册推送通知:

在我的app delegate的didFinishLaunchingWithOptions方法中:

[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|
                                                UIRemoteNotificationTypeAlert|
                                                UIRemoteNotificationTypeSound];

我的应用代理中添加的方法:

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

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

我访问过的资源表明这个代码块

4 个答案:

答案 0 :(得分:18)

您可以随时进行注册通话 - 只有当您在应用中知道您希望用户接收推送通知时,才可以这样做。

两个应用程序委托回调必须在您的应用程序委托中,因为您在应用程序委托上注册通知类型而您只有一个。我建议使用一个应用程序委托方法来调用然后进行注册,你可以通过[[UIApplication sharedApplication] delegate]从你的视图控制器调用它(将该调用的结果转换为你的应用程序委托类)。

答案 1 :(得分:11)

这个答案是肯德尔·赫尔姆斯特特·格尔纳(Kendall Helmstetter Gelner)的“投票结果”回复(肯德尔的答案有0票,但对我来说效果很好,我没有足够的积分来表达答案)。遵循Kendall的建议,我的视图控制器,CMRootViewController.m - >

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

并且两个应用程序委托回调在我的app委托中,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];
}
谢谢Kendall。

答案 2 :(得分:5)

最好的方法是,在您的app delegate方法中处理删除通知,使用NSNotificationCenter发送通知

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

然后使用NSNotificationCenter添加任何感兴趣的UIViewControllers作为remoteNotification通知的观察者。

答案 3 :(得分:1)

SWIFT 3及以上

从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)")
    }
}