Push notification delegate method issue

2019-09-07 00:50发布

问题:

I am new to Objective C. In my app i need to implement push notification, i have created new app ID and i have created new provisioning profile also. i have finished all the steps mentioned in this link

i have declared this delegate function in my appDelegate .m file.

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 

        NSString *deviceTokens = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
        deviceTokens = [deviceTokens stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSLog(@"registered device token %@", deviceTokens);
        self.deviceToken = deviceTokens; 
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { 

    NSString *str = [NSString stringWithFormat: @"Error: %@", err];
    NSLog(@"String %@",str);    

}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    for (id key in userInfo) {
        NSLog(@"key: %@, value: %@", key, [userInfo objectForKey:key]);
    }    

}

But this delegate functions are not called. please help me to fix this issue.

回答1:

In your AppDelegated didfinishLaunching with options write the following line

[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];


回答2:

Add this code to your application didFinishLaunchingWithOptions method, inside your app delegate

if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {

    //We check because ios7 cannot respond to this method and there will be a crash..
    UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;

    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];

    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
    [application registerForRemoteNotifications];
}
else {
    //This will work on ios7 devices and below
    UIRemoteNotificationType types = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
    [application registerForRemoteNotificationTypes:types];
    [application registerForRemoteNotifications];
}

return YES;


回答3:

Use new delegate method

Swift: func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)