Can I use Apple Push Notification Service to have

2019-02-26 06:32发布

问题:

My Algorithm wishes to work this way-

If some desired event occurs at my server then I wish to send a small amount of data to every user my app (foreground or background). But, instead of notifying the user I wish my app to do some computation on data and acknowledge server. Remember user must not be notified.

回答1:

You can use the content-available key in the push notification data and application:didReceiveRemoteNotification:fetchCompletionHandler:. It could be considered a bit of a hack for your use case and if you try to use it too much you will get limited by Apples system.



回答2:

You can do this on iOS 7. See the section "Fetching Small Amounts of Content Regularly" at iOS App Programming Guide.



回答3:

You can send "empty" push notification (no text, no sound, no icon). This kind of notifications is allowed and can be used for synchronization with server (to avoid the expensive repetitive polling from the app side).

If your app is not running then such a notification won't show up among springboard notifications.

If it is running then it will receive notification - you just have to make sure you don't show the empty ones (if you are also using notifications with actual contents). Your iOS code would look a bit like:

- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
{
    NSString *message = nil;
    id alert = [userInfo objectForKey:@"aps"];

    if ([alert isKindOfClass:[NSString class]])
    {
        message = alert;
    }
    else if ([alert isKindOfClass:[NSDictionary class]])
    {
        message = [alert objectForKey:@"alert"];
    }

    if (message)
    {
        if (![message isEqualToString:@""])
        {
            UIAlertView *alertView = [[UIAlertView alloc]
                                      initWithTitle: @"notification"
                                      message: message
                                      delegate: nil
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
            [alertView show];
        }
    }
    else
    {
      //this was an empty notification - here you can enqueue
      //your server-synchronization routine - asynchronously if possible
    }
}

If you don't intend to use any "real" notifications you don't even have to bother with decoding the message.

If you use ApnsPHP your message generation code would look like this:

$message = new ApnsPHP_Message($device_apns_token);
$message->setText('');
$message->setSound('');
$message->setExpiry(3600);
$push->add($message);