三、 静默推送

静默推送是干嘛的?有什么作用,苹果为何提供静默推送?如何去触发静默通知?

一、静默通知调用方法的研读

通过观看 WWDC ,方知有个静默通知东东,于是想着如何实现它,它有什么注意点?通过后面查询资料才知道,静默远程通知会调用如下的方法。

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler NS_AVAILABLE_IOS(7_0);

上面的方法作用是告诉应用,远程通知已经来了,远程通知捎点东西,让应用自己去拿一下。


参数说明

  • application application 单例对象。

  • userInfo 这个参数是远程通知带来的东西,userInfo 里面可能包含 badge 和 通知声音,和通知展示给用户的信息,通知的标识和自定义的数据哦。远程服务器推送的内容是 Json 格式的字典,而 iOS 会将其推送的内容转化成 NSDictonary 对象。

  • handler 当下载操作完成时,handler 将会被执行。当调用 handler 方法时,请传入 UIBackgroundFetchResult 枚举值最能描述下载操作结果。你一定要尽快的调用 handler 方法


UIBackgroundFetchResult 枚举的意思

  • UIBackgroundFetchResultNewData
    新的数据下载成功

  • UIBackgroundFetchResultNoData
    没有新的数据下载

  • UIBackgroundFetchResultFailed
    下载新的数据失败


二、讨论
  • 1、 静默通知能下载多久?
    有30秒的下载时间
    官方说明:Your app has up to 30 seconds of wall-clock time to process the notification and call the specified completion handler block. In practice, you should call the handler block as soon as you are done processing the notification。
  • 2、静默通知能在前台下载吗?
    已经验证,是前台和后台都能下载。

  • 3、静默通知后台下载有限制吗?
    有限制,苹果会监听下载的时间、电量消耗。如果应用处理静默通知下载去花费太多的电量,将来的静默通知可能不能及时唤醒应用的。
    官方说明: The system tracks the elapsed time, power usage, and data costs for your app’s background downloads. Apps that use significant amounts of power when processing remote notifications may not always be woken up early to process future notifications.


三、配置和代码实现
  • 1、配置
    如果你不明如何配置远程推送证书,请参考从零开始创建iOS远程推送证书里面有,教你如何配置推送证书。
    另外要在 Xcode 中操作两个步骤,一个是允许后台下载,另一个是允许接受远程通知。
    允许后台下载
允许接受远程通知
  • 2、代码
#import "AppDelegate.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import 
#endif

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //注册通知
    if ([[UIDevice currentDevice].systemVersion doubleValue]>= 10.0) {
        //iOS 10 特有
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionAlert | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                NSLog(@"打印成功");
            }
        }];
        center.delegate = self;
        
    }else if([[UIDevice currentDevice].systemVersion doubleValue]>8){
        //分类
        UIMutableUserNotificationCategory *category = [[UIMutableUserNotificationCategory alloc] init];
        
        //分类标识
        category.identifier = @"iOS 8 Category id";
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:[NSSet setWithObject:category]];
        
        [application registerUserNotificationSettings:settings];
    }
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    return YES;
}
#pragma mark - iOS 10 通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    NSLog(@"helloworld");
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}
// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
    
    completionHandler();
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    NSLog(@"%@",[NSString stringWithFormat:@"device Token %@",deviceToken]);
}


-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    if (error) {
        NSLog(@"%@",error);
    }
}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    NSLog(@"iOS 10 以下收到通知");
}

#pragma mark -  静默通知
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    NSDictionary *dict = userInfo[@"aps"];
    NSLog(@"%@",dict[@"name"]);
    completionHandler(UIBackgroundFetchResultNewData);
}

@end

四、推送远程内容

提供一个强大的基于 MAC 的推送服务器,SmartPush。运行 Xcode 会出现如下图的弹框。

Snip20170727_42.png

注意:请使用最新的 notification 格式

  • 不能加alert,如果加入了alert就不是静默推送了,本人试过。
  • 务必加"content-available" : 1
  • sound感觉也不能加,加入的话就不是静默推送,但是我在测试中有加入,也是可以的,建议不要加。

服务器推送的内容如下。

{
    "aps": { "content-available" :  1,"name":"oliver"
            }
}

如果服务器推送的内容包含 alert 就不是静默推送了,就是 一般的远程推送啦。

 {
 "aps": {
 "alert": "This is some fancy message.",
 "badge": 1,
 "sound": "default",
 "mutable-content": "1",
 "imageAbsoluteString": "http://www.gaoxiaogif.com/d/file/201707/small1dd8ecd6f646f3785778c92ae68bcfda.gif"
 ,
 "title" :"noticefyTitle",
 "subtitle":"subtittle","fileType":"gif"
 }
 }

五、结语

静默通知是让应用在后台悄悄的下载东东,这样用户启动应用时,会给用户一种惊喜,苹果还是为了提高用户体验出发的。
如果不正确的地方,请告知,感恩!!

你可能感兴趣的:(三、 静默推送)