新建好一个项目,AppDelegate.m
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
// 当app被杀掉,然后从通知中心,或者在锁屏状态显示的推送。用户点击了这一个推送,进而启动了app。在这个方法里边,获得点击的推送内容,在launchOptions这个参数里边找
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 明确要使用推送服务的哪些类,以下代码注册了
// UIUserNotificationTypeBadge 应用程序图标标记(右上角显示文字)
// UIUserNotificationTypeSound 声音
// UIUserNotificationTypeAlert 在锁定屏幕上显示
UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
[application registerUserNotificationSettings:setting];
[application registerForRemoteNotifications];
// 查看用户在系统设置的"通知"里,开启了哪些服务
if ([application currentUserNotificationSettings].types == UIUserNotificationTypeNone) {
NSLog(@"注册推送服务失败");
}
return YES;
}
// 注册推送服务成功,需要将deviceToken发送给服务器
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(@"%@", deviceToken);
}
// 此函数,只会进入一次。如果用户第一次点击了不允许,那么下一次再执行registerForRemoteNotifications就不会进入
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"注册推送服务失败");
}
// 接收到了一个远程推送,或者用户从通知栏点击进入了app(App切换到了后台,但是没有被杀掉)
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// 在userInfo这个字典里,aps里边有3个内容:alert、badge、sound
// 对于app来说,只显示文字内容就可以了
// 文字内容在userInfo[@"aps"][@"alert"]
// aps - Apple Push Notification Service
UIAlertController *alert = [UIAlertController alertControllerWithTitle:userInfo[@"aps"][@"alert"] message:nil preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}]];
[self.window.rootViewController presentViewController:alert animated:YES completion:^{
}];
}
@end