iOS拦截推送通知

Uff*_*ffe 5 objective-c push-notification apple-push-notifications ios ios7

我正在使用推送通知进行应用,我目前正在使用pushbots进行推送通知.我想知道是否有任何方法可以拦截应用程序收到的通知,并在设备上显示通知之前检查通知.如果通知中的数据不正确,根本不显示通知?这是推特机器人的可能吗?或者我需要自己完成这一切吗?

Agu*_*les 17

是的,您可以使用本地通知来实现此行为.

您可以在没有的情况下配置有效负载alert,"content-available": "1"因此您的应用程序可以接收通知,而无需向用户显示.

// Payload
{
    aps: {
       "content-available": 1
    },
    text: 'my alert message' // your custom info
} 
Run Code Online (Sandbox Code Playgroud)

在您的应用代码中,将通知注册为

// Register notifications
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
 UIRemoteNotificationTypeNewsstandContentAvailability];
Run Code Online (Sandbox Code Playgroud)

然后,关键是application:didReceiveRemoteNotification:fetchCompletionHandler:根据某些条件触发方法中的本地通知

- (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler 
{

    NSLog(@"push data package: %@", userInfo);

    // Retrieve your data        
    NSString *text = [userInfo objectForKey:@"text"];

    BOOL mustShow = YES;
    // Only show notification if app is background and your custom condition
    if ((state == UIApplicationStateInactive || state == UIApplicationStateBackground) 
         &&  mustShow) {
        // Raise the local notification a second after received
        UILocalNotification* localNotification = [[UILocalNotification alloc] init];
        localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
        localNotification.alertBody = text;
        localNotification.timeZone = [NSTimeZone defaultTimeZone];
        localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;

        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,您可以在将"显示"通知发送给用户之前"拦截"通知.


Era*_*ran 2

您无法阻止通知在到达设备后显示(假设它包含字典alert中的字段aps- 如果不包含,则无论如何都不会显示通知)。

您应该在服务器中确定哪些通知应发送到哪些设备令牌。如果您的功能需要,您可以将设备令牌与数据库中的用户相关联。

即使您的请求是可能的,向安装您的应用程序的所有设备发送通知,然后仅在其中的一小部分设备中显示通知,效率也会非常低。