简体   繁体   English

iOS在应用程序中注册推送通知

[英]iOS Registering for Push Notifications within Application

Q1. Q1。 Do I have to do this at the start of my App? 在我的应用程序开始时我是否必须这样做? Or can I trigger the prompt to allow/not-allow at any point in my app? 或者我可以在我的应用程序中的任何位置触发允许/不允许的提示吗?

Q2. Q2。 Is there a way to find out if the user clicked yes/no ? 有没有办法找出用户是否点击了是/否? (callback?) (打回来?)

Q3. Q3。 If the user has already clicked no, (in a previous session), will my prompt actually fire? 如果用户已经点击否,(在之前的会话中),我的提示是否会实际触发? Or do I need to tell the user to go to their phone settings and enable it there? 或者我是否需要告诉用户转到他们的手机设置并在那里启用它?

Reason being is I have an app which has a section inside it called "Notifications" whereby they can enable/disable to receive notifications on certain things, so I only want to prompt them to enable etc. when they are in this section not at the start of the App. 原因是我有一个应用程序,里面有一个名为“通知”的部分,他们可以启用/禁用接收某些事情的通知,所以我只想提示他们启用等等,当他们在这部分而不是在应用程序的开始。

A1: No, it doesn't have to be at the start of the app. A1:不,它不一定是应用程序的开头。 You can invoke registerForRemoteNotificationTypes from anywhere in the code. 您可以从代码中的任何位置调用registerForRemoteNotificationTypes。

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

You will need to handle following delegates methods(in delegate) which gets called on successful/fail registering for push notification. 您将需要处理以下委托方法(在委托中),这些方法在成功/失败注册推送通知时被调用。

// Delegation methods
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
    const void *devTokenBytes = [devToken bytes];
    self.registered = YES;
    [self sendProviderDeviceToken:devTokenBytes]; // this will send token to your server's database
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    NSLog(@"Error in registration. Error: %@", err);
}

A2: Yes you can. A2:是的,你可以。 There are two possible scenarios. 有两种可能的情况。 If your application is not running, you will handle push notification in didFinishLaunchingWithOptions. 如果您的应用程序未运行,您将在didFinishLaunchingWithOptions中处理推送通知。 In this case if user has selected "open" in the message alert or clicked on Banners(depends on user's settings), your application will automatically start and you can handle user parameters passed in push notification. 在这种情况下,如果用户在消息提醒中选择了“打开”或单击了横幅(取决于用户的设置),您的应用程序将自动启动,您可以处理推送通知中传递的用户参数。

 /* Push notification received when app is not running */
 NSDictionary *params = [[launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"] objectForKey:@"appsInfo"];

    if (params) {
        // Use params and do your stuffs
    }

If your application is already running, push notification will be delivered to application:didReceiveRemoteNotification: delegate method where you can simply present UIAlertView with the message in push notification and handle alertView delegates OK/Cancel button click in standard way. 如果您的应用程序已在运行,则推送通知将传递给application:didReceiveRemoteNotification: delegate方法,您可以在推送通知中使用消息简单地呈现UIAlertView并处理alertView委托OK / Cancel按钮以标准方式单击。

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSDictionary *apsInfo = [userInfo objectForKey:@"apsinfo"]; // This appsInfo set by your server while sending push

    NSString *alert = [apsInfo objectForKey:@"alert"];

    UIApplicationState state = [application applicationState];

    if (state == UIApplicationStateActive) {
        application.applicationIconBadgeNumber = 0;

        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"Push Notification"
                                                            message:alert
                                                           delegate:self
                                                  cancelButtonTitle:@"NO"
                                                  otherButtonTitles:@"YES"];
        [alertview show];
        [alertview release];

    } else {
        [self setTabs:contentsInfo];
     }
}


- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex != [alertView cancelButtonIndex]) {
     // User pressed YES, do your stuffs
     }
}

A3: If user has refused to accept push notification from your app then its didFailToRegisterForRemoteNotificationsWithError and you hence you will not get user's devToken which is required to be on your server to send push notification to that user. A3:如果用户拒绝接受来自您的应用程序的推送通知,那么它的didFailToRegisterForRemoteNotificationsWithError将导致您无法获得用户的devToken,该服务器需要在该服务器上向该用户发送推送通知。 If user initially accept but later on if he changed settings to disable your push notification then Apple server will not send your push notification to that user. 如果用户最初接受但稍后如果他更改了设置以禁用推送通知,那么Apple服务器将不会将推送通知发送给该用户。 In this case that user's UDID will appear in Feedback service and ideally your server should remove that user's UDID from the database and stop sending push notification to that users going forward. 在这种情况下,用户的UDID将出现在反馈服务中,理想情况下,您的服务器应从数据库中删除该用户的UDID,并停止向该用户发送推送通知。 If you keep sending invalid push notification, Apple server might drop your connection silently and you will not able to send any push notifications. 如果您继续发送无效推送通知,Apple服务器可能会静默删除您的连接,您将无法发送任何推送通知。

See Apple Push Notification docs for details on implementation. 有关实施的详细信息,请参阅Apple推送通知文档。

  • Q1 It's not necessary to put push register at app launch, but some do put it in application: didFinishLaunchingWithOptions: to somehow ensure the device token is successfully stored on developer's server. Q1没有必要将推送寄存器放在应用程序启动时,但有些确实将它放在application: didFinishLaunchingWithOptions:以某种方式确保设备令牌成功存储在开发人员的服务器上。
  • Q2 What the "yes/no" for here? Q2这里的“是/否”是什么? If you mean the "yes/no" on "if receive push notification", then if the user clicked "yes", the delegate application: didRegisterForRemoteNotificationsWithDeviceToken will be triggered, otherwise not. 如果你的意思是“如果收到推送通知”的“是/否”,那么如果用户点击“是”,则会触发委托application: didRegisterForRemoteNotificationsWithDeviceToken ,否则不会。
  • Q3 If the user click "no" to reject receiving push notification, then either you can later remind him to turn it on in settings, or have a function, like a UISwitch thing, to enable users to trigger [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound)]; Q3如果用户单击“否”拒绝接收推送通知,那么您可以稍后提醒他在设置中打开它,或者具有UISwitch之类的功能,以使用户能够触发[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound)]; again. 再次。

You can use following tutorial for swift( Visit Link ) and use following simple code for objective-c for Apple Push Notification. 您可以使用以下swift教程( 访问链接 )并使用以下简单代码进行Apple推送通知的objective-c。

  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
        {
         // iOS 8 Notifications
            [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound |UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
            [application registerForRemoteNotifications];
        }
        return YES;
    }


    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
        NSLog(@"Did Register for Remote Notifications with Device Token (%@)", deviceToken);
    }

    - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

        NSLog(@"Did Fail to Register for Remote Notifications");
        NSLog(@"%@, %@", error, error.localizedDescription);
    }

    -(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
        NSLog(@"%@",userInfo);
    }

Answer for for question:2 in iOS 10. 回答问题:iOS 10中的2。

In the iOS:10, a completion handler is implemented. 在iOS:10中,实现了完成处理程序。 Hence you will be notified immediately within the completion handler block. 因此,您将在完成处理程序块中立即得到通知。

if([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.f){
    UNUserNotificationCenter* notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
    [notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge completionHandler:^(BOOL granted, NSError * _Nullable error) {
        NSLog(@"grant Access:%d",granted);
    }];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM