如何在 APNS 的背景前景上使用相同的通知

How to use same notification on Background Foreground in APNS

我正在开发 APNS。 当我发送 APNS 时,提供 url 并移动 url。 APNS 已成功,但当应用程序 运行 时,它无法在前台接收通知。 但是在后台,它的工作。当它在前台时 它只是在没有通知的情况下移动到 url。 你能帮帮我吗?

    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    UIApplicationState state = [UIApplication sharedApplication].applicationState;
    BOOL state_active = (state == UIApplicationStateActive);
    dic_apns = [userInfo objectForKey:@"aps"];

    // alert export
    NSString * msg = [dic_apns objectForKey:@"alert"];
    NSString * eventcode = [userInfo objectForKey:@"eventcode"];
    [[NSUserDefaults standardUserDefaults] setValue :msg forKey:@"push_msg"];
    [[NSUserDefaults standardUserDefaults] setValue :eventcode forKey:@"eventcode"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    NSLog(@"APNS : msg=%@ | eventcode=%@", msg , eventcode);
    [self goto_link];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];

}
-(void) goto_link{

    NSString * eventcode = [[NSUserDefaults standardUserDefaults] valueForKey:@"eventcode"];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@", _MAIN_URL, _PUSH_PARAM, eventcode]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    ViewController* main = (ViewController *)  self.window.rootViewController;

    if (!main.webview_sin )
    {
        NSLog(@"main.webView  is nil!!!");
    }

    [main.webview_sin loadRequest:request];
}

when it's on foreground it just move to url without notification

这是预期的行为。如果您的应用是 运行.

,则不会显示通知

您可以改为使用 UIAlertController 向用户显示消息

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
{
    if (application.applicationState == UIApplicationStateActive)        
    {               
        UIAlertController *alertController = [UIAlertController
                          alertControllerWithTitle:@"Notification"
                          message:/* Get the message from APS */
                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction 
        actionWithTitle:@"Dismiss"
                  style:UIAlertActionStyleCancel
                handler:^(UIAlertAction *action)
                {
                    //Do Nothing
                }];
        [alertController addAction:cancelAction];
        [/*pick an appropriate view controller */ presentViewController:alertController animated:YES completion:nil];
    }    
}

部分代码改编自here