三、<iOS 远程推送> 静默推送

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

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

通过观看 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 枚举的意思


二、讨论
  • 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 <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@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"
 }
 }

五、结语

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 180,425评论 25 708
  • 写作原因:网上看了很多推送文章都没有完美的解答我的疑惑;主要有以下两点,1:推送来了我点击应用图标进入应用怎么取到...
    Thebloodelves阅读 4,702评论 26 71
  • 顾城诗集摘选 水乡 清明 淡紫色的风 颤动着—— 溶去了繁杂、喧嚷 花台布 和那布满油迹的曲调…...
    蜗牛不会飞阅读 562评论 0 1
  • 河水喜爱春天 但是对与冬天也是无奈 河水修长的倩影,暗恋着春风 缠绵的情话,秋雨一般温柔,绵长 无奈春风无情,转身...
    泰安左眼皮跳跳阅读 261评论 0 8
  • 认识这个女生是因为父母在一起工作,初次见面看得出。她对我家一清二楚,家庭的原因是第一因素。 喜欢,喜不喜欢,只是很...
    potato_车阿明阅读 321评论 0 0

友情链接更多精彩内容