关于iOS 9之前的本地推送,本地推送杀掉进程后到底能不能收到?

缘起一个面试:

面试官:“本地推送,在杀掉进程以后还可以收到吗?”
(非常肯定的):“可以的”
面试官:“并不能,不信你回去写个demo吧”
:“我写过本地推送,确实是可以的啊”
面试官:“如果杀掉进程后,还能收到本地推送,那还要远程推送干什么呢???”
:“。。。。。。”

本来无意来计较这件事,但是面试过程中,面试官态度比较强硬、瞧不起人,让人很反感,但还是不说哪家公司了

这个结果根本不意外吧,稍微做过一两年开发的都知道

今天我就写一个Demo,然后再唠叨原理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 以下代码只为简单的验证问题,不是教程,诸位凑合看吧
// 注册通知
+ (void)registerPush
{
UILocalNotification *localNotification = [[UILocalNotification alloc] init];

localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:15];
localNotification.alertBody = @"I am a LocalNotification!";
localNotification.alertAction = @"check";
localNotification.hasAction = YES;
localNotification.applicationIconBadgeNumber = 1;

[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

/**
* iOS 8 以后的版本需要添加推送类型
* 官方文档:In iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:] before being able to schedule and present UILocalNotifications
*/
+ (void)registerPushType
{
if (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_8_0) {
UIUserNotificationType type=UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound;
UIUserNotificationSettings *setting=[UIUserNotificationSettings settingsForTypes:type categories:nil];
[[UIApplication sharedApplication]registerUserNotificationSettings:setting];
}
}

// 清除角标
+ (void)clearIconBadgeNumber
{
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

本地推送的机制

看官方文档点击这里,第一句话是:
The operating system is responsible for delivering local notifications at their scheduled times; the app does not have to be running for this to happen.Although local notifications are similar to remote notifications in that they are used for displaying alerts, playing sounds, and badging app icons, they are composed and delivered locally and do not require connection with remote servers.
明确说明了本地推送是由操作系统负责触发的,不需要App本身,后边还特别注明了尽管与远程推送一样的效果,但是不需要与远程服务器链接。

也就是说,无论有无网络连接,App进程是否被杀掉,都可以接收到本地推送。

管理(or触发?)本地推送的两个方法

1
2
3
- (void)presentLocalNotificationNow:(UILocalNotification *)notification;

- (void)scheduleLocalNotification:(UILocalNotification *)notification; // copies notification

第一个,直接触发,平时我用的很少。
第二个,把本地通知交给操作系统,操作系统根据通知内包含的信息决定何时何地推送这条本地推送。(附:本地推送会被系统拷贝一份副本,便于触发后的释放)

写在最后,做技术的还是少装13,我不知道这位面试官为何会万分肯定在进程被杀掉之后是收不到本地推送的,难道连文档都不看就出来教育别人了么???

显示 Gitment 评论