iOS开发 ☞ 推送通知(Push Notification)

来源:互联网 发布:c语言基础知识txt下载 编辑:程序博客网 时间:2024/05/25 21:36

推送通知分为两种:本地推送通知(Local Notification) 和 远程推送通知(Remote Notification)
一、本地通知
无需网络连接
当应用处于非前台状态的时候(无论是锁屏、后台、还是未运行),如果用户点击了通知,便会打开应用程序。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {//iOS8.0 以后,发送本地通知需要添加的代码,效果见下图if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.f) {        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];        [application registerUserNotificationSettings:settings];    }    return YES;}

必须获取用户权限:
这里写图片描述

发送通知代码:- (IBAction)pressSend:(id)sender {    UILocalNotification *local = [[UILocalNotification alloc] init];    local.fireDate = [NSDate dateWithTimeIntervalSinceNow:5.f];    local.alertBody = @"我是本地通知";    local.applicationIconBadgeNumber = 999;    [[UIApplication sharedApplication] scheduleLocalNotification:local];}

其他属性:

- (instancetype)init NS_DESIGNATED_INITIALIZER;- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;// timer-based scheduling@property(nullable, nonatomic,copy) NSDate *fireDate;// the time zone to interpret fireDate in. pass nil if fireDate is an absolute GMT time (e.g. for an egg timer).// pass a time zone to interpret fireDate as a wall time to be adjusted automatically upon time zone changes (e.g. for an alarm clock).@property(nullable, nonatomic,copy) NSTimeZone *timeZone;@property(nonatomic) NSCalendarUnit repeatInterval;      // 0 means don't repeat@property(nullable, nonatomic,copy) NSCalendar *repeatCalendar;// location-based scheduling// set a CLRegion object to trigger the notification when the user enters or leaves a geographic region, depending upon the properties set on the CLRegion object itself. registering multiple UILocalNotifications with different regions containing the same identifier will result in undefined behavior. the number of region-triggered UILocalNotifications that may be registered at any one time is internally limited. in order to use region-triggered notifications, applications must have "when-in-use" authorization through CoreLocation. see the CoreLocation documentation for more information.@property(nullable, nonatomic,copy) CLRegion *region NS_AVAILABLE_IOS(8_0);// when YES, the notification will only fire one time. when NO, the notification will fire every time the region is entered or exited (depending upon the CLRegion object's configuration). default is YES.@property(nonatomic,assign) BOOL regionTriggersOnce NS_AVAILABLE_IOS(8_0);// alerts@property(nullable, nonatomic,copy) NSString *alertBody;      // defaults to nil. pass a string or localized string key to show an alert@property(nonatomic) BOOL hasAction;                // defaults to YES. pass NO to hide launching button/slider@property(nullable, nonatomic,copy) NSString *alertAction;    // used in UIAlert button or 'slide to unlock...' slider in place of unlock//随便传入一个字符串都会以启动图片启动@property(nullable, nonatomic,copy) NSString *alertLaunchImage;   // used as the launch image (UILaunchImageFile) when launch button is tapped@property(nullable, nonatomic,copy) NSString *alertTitle NS_AVAILABLE_IOS(8_2);  // defaults to nil. pass a string or localized string key// sound@property(nullable, nonatomic,copy) NSString *soundName;      // name of resource in app's bundle to play or UILocalNotificationDefaultSoundName// badge@property(nonatomic) NSInteger applicationIconBadgeNumber;  // 0 means no change. defaults to 0// user info@property(nullable, nonatomic,copy) NSDictionary *userInfo;   // throws if contains non-property list types// category identifer of the local notification, as set on a UIUserNotificationCategory and passed to +[UIUserNotificationSettings settingsForTypes:categories:]@property (nullable, nonatomic, copy) NSString *category NS_AVAILABLE_IOS(8_0);@end

接到本地通知,程序一定处于非前台状态,所以当设置了徽标时,点击应用程序或者直接点击通知时,应当清除徽标

- (void)applicationWillEnterForeground:(UIApplication *)application {    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.    [application setApplicationIconBadgeNumber:0];}

监听方法:

首先了解应用程序的状态
typedef NS_ENUM(NSInteger, UIApplicationState) {
//前台
UIApplicationStateActive,
//非活跃
UIApplicationStateInactive,
//后台
UIApplicationStateBackground
} NS_ENUM_AVAILABLE_IOS(4_0);

//用户点击了通知:进入前台的状态 或者 应用已经在前台 会执行下面的方法,收到通知,但是如果程序已经被杀死,点击通知是不会执行这个方法的。所以还需要在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法里另行做判断(通过启动字典判断)。- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {    //我们可以通过notification.userInfo 获得通知的额外信息,当然,在发送通知时,我们要给通知的对象设置userInfo的内容。}
if (launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]){    }

二、远程推送
1、原理图:
这里写图片描述
代码实现:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.f) {        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];        [application registerUserNotificationSettings:settings];        [application registerForRemoteNotifications];    }else {        [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound ];    }    if (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]){    }

收到DeviceToken

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {//把收到的deviceToken发送给自己的服务器,可以通过deviceToken.description 拿到字符串形式}

监听用户点击通知:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {}

2、证书配置
前言:
我们常说的配置证书,其实是指哪台电脑具备的能力,因为我们要上传CSR文件,而CSR文件是苹果确定电脑的手段,推送证书也不例外,下面以推送调试证书为例。

例一:
很多App上线时并没有集成远程推送功能,这就涉及到给已经上线的应用添加远程推送功能,如果是这样,我们可以用第一种方式创建远程推送证书,介绍如下:
首先,和创建真机调试证书一样
这里写图片描述
选择推送证书项:
这里写图片描述
选择推送调试的AppID:
这里写图片描述
上传CSR文件:
这里写图片描述

总结一下:与真机调试不一样的地方在于,这里的调试证书要与AppID绑定在一起,当然合情合理,因为这个证书是单独存在的,与调试证书没有任何关系,配置文件也不会关联这个证书,当然得自己关联应用程序了,下载下来安装就可以咯。

例二:
假如我们第一次上架应用程序就带远程推送功能,我们可以这么做:

创建appID,选择明确的appID,勾选推送。
点击创建的appID,查看推送功能,此时显示configrable
点击edit
添加推送调试证书(发布就添加推送发布证书)
测试推送功能当然需要真机调试,所以必须有真机调试证书
生成配置文件
安装证书即可

1 0
原创粉丝点击