前言:这段时间做了一个项目,项目中有一个要求就是在APP切换到UIApplicationStateBackground模式下,依然可以收到通知。但因为我这边使用了socket,在UIApplicationStateBackground模式下,socket还没有断掉,此时也不走苹果推送,所以我就想到了NSNotificationCenter,在APP进入UIApplicationStateBackground模式下,根据NSNotificationCenter做了一个推送。下面是详细步骤:
1.首先就是要注册通知,将通知的代理事件设为self。在- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {}这个方法中编写,如图1所示:

2.获取到推送,如图2所示,将推送通过NSNotificationCenter传到AppDelegate里的- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {}这个方法中,并在此方法中接收,接收方法是
[[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(location:) name:@"Post"object:nil];
注:接收方法中的name必须和传入的name名字相同

3.将接收到的通知显示在通知栏,首先要实现第2步所说的location:方法,如图3所示:

接着实现NSNotificationCenter的代理方法,如图4所示:

- (void)userNotificationCenter:(UNUserNotificationCenter*)center willPresentNotification:(UNNotification*)notification withCompletionHandler:(void(^)(UNNotificationPresentationOptions))completionHandler{}
注:a.此为NSNotificationCenter接收到通知的事件,这是iOS10接收推送的方法,将本体推送和远程推送合二为一,可以通过response. notification.request.trigger来区分,UNPushNotificationTrigger(远程通知)远程推送的通知类型
b.UNTimeIntervalNotificationTrigger(本地通知)一定时间之后,重复或者不重复推送通知。我们可以设置timeInterval(时间间隔)和repeats(是否重复)。
c.UNCalendarNotificationTrigger(本地通知)一定日期之后,重复或者不重复推送通知例如,你每天8点推送一个通知,只要dateComponents为8,如果你想每天8点都推送这个通知,只要repeats为YES就可以了。
d.UNLocationNotificationTrigger(本地通知)地理位置的一种通知,当用户进入或离开一个地理区域来通知。在CLRegion标识符必须是唯一的。因为如果相同的标识符来标识不同区域的UNNotificationRequests,会导致不确定的行为。
4.通知的点击事件,需实现NSNotificationCenter的这个代理方法,具体如图5所示:
- (void)userNotificationCenter:(UNUserNotificationCenter*)center didReceiveNotificationResponse:(UNNotificationResponse*)response withCompletionHandler:(void(^)())completionHandler{}

结尾:以上就是通过NSNotificationCenter实现通知的详细步骤,如有不当之处,欢迎指正😁
END
网友评论