您的位置:首页 > 其它

LocalNotification 与远程通知的是如何操作的?

2016-04-26 23:15 369 查看
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

/*
// 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; 当luanch 按钮被点击后的luanch图片
// 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; app的角标  // 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);

*/

/*
UIUserNotificationTypeNone    = 0,  没有
UIUserNotificationTypeBadge   = 1 << 0,  角标
UIUserNotificationTypeSound   = 1 << 1,  通知可以有声音
UIUserNotificationTypeAlert   = 1 << 2,  通知有弹窗
*/

//设置分类
UIMutableUserNotificationCategory * category = [[UIMutableUserNotificationCategory alloc]init];

category.identifier = @"cate";

/*
// The unique identifier for this action.
@property (nullable, nonatomic, copy) NSString *identifier; 标识

// The localized title to display for this action.
@property (nullable, nonatomic, copy) NSString *title;  标题

// The behavior of this action when the user activates it.
@property (nonatomic, assign) UIUserNotificationActionBehavior behavior
行为
NS_AVAILABLE_IOS(9_0);

// Parameters that can be used by some types of actions.
@property (nonatomic, copy) NSDictionary *parameters NS_AVAILABLE_IOS(9_0);

// How the application should be activated in response to the action.
@property (nonatomic, assign) UIUserNotificationActivationMode 模式 activationMode;

// Whether this action is secure and should require unlocking before being performed. If the activation mode is UIUserNotificationActivationModeForeground, then the action is considered secure and this property is ignored.
@property (nonatomic, assign, getter=isAuthenticationRequired) BOOL authenticationRequired;

// Whether this action should be indicated as destructive when displayed.
@property (nonatomic, assign, getter=isDestructive) BOOL destructive;

*/

UIMutableUserNotificationAction * action = [[UIMutableUserNotificationAction alloc]init];

action.title = @"哈哈";

action.identifier = @"id1";

action.activationMode = UIUserNotificationActivationModeBackground;

action.authenticationRequired = NO;

action.destructive = YES;

//设置了动作的行为问为文本输入模式,
action.behavior = UIUserNotificationActionBehaviorTextInput;
UIMutableUserNotificationAction * action1 = [[UIMutableUserNotificationAction alloc]init];

//设置动作属性
action1.title = @"嘻嘻嘻";

action1.identifier = @"id2";

action1.activationMode = UIUserNotificationActivationModeBackground;

action1.authenticationRequired = NO;

action1.destructive = YES;//设置动作按钮的颜色, yes 为红色, no 为蓝色

[category setActions:@[action,action1] forContext:UIUserNotificationActionContextDefault];

// | 位或  << 左移
UIUserNotificationSettings * settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeNone | UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:[NSSet setWithObjects:category, nil]];

//注册用户通知

[[UIApplication sharedApplication]registerUserNotificationSettings:settings];

}

//点击屏幕定制通知 5 秒后发送通知
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

//创建本地通知 (iOS 8.0 之后,注册通知需要注册用户通知)
UILocalNotification * localNotification = [[UILocalNotification alloc]init];

//配置通知
//5秒后发送通知
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];

localNotification.alertBody = @"Zhq:在吗?";

localNotification.alertTitle = @"一款牛逼的聊天软件";

localNotification.applicationIconBadgeNumber = 10;

localNotification.alertAction = @"聊天中";

localNotification.alertAction =@"hahahahha";

localNotification.hasAction = NO;

localNotification.category = @"cate";

localNotification.userInfo = @{@"name":@"xiaohua"};

//定制通知
[[UIApplication sharedApplication]scheduleLocalNotification:localNotification];

//系统展示通知

}


  

#import "AppDelegate.h"
#import "jumpViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

//接收到本地通知是调用 (应用的前后台都会执行这个方法 , 当应用程序挂了就不会执行这个方法)
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{

NSLog(@"didReceiveLocalNotification");

if (![[NSUserDefaults standardUserDefaults]boolForKey:@"Foreground"]) {

[self jumpVc];
}

}

-(void)jumpVc {

UIStoryboard * sb = [UIStoryboard storyboardWithName:@"jump" bundle:nil];

jumpViewController * jv = [sb instantiateInitialViewController];

self.window.rootViewController = jv;

}

//点击本地通知Action就会执行下面两个方法 如果实现withResponseInfo方法,此方法就不会调用
-(void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void (^)())completionHandler{

//通过Action 的idetifier 来分别执行不同的业务逻辑
NSLog(@"i%@" , identifier);

completionHandler();

}

//NS_ENUM_AVAILABLE_IOS(9_0) __TVOS_PROHIBITED,当设置action的行为为textInput 就可以调用这个方法,通过responseInfo获取用糊输入的内容,还做其他业务逻辑
-(void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void (^)())completionHandler{

NSLog(@"%@",responseInfo[@"UIUserNotificationActionResponseTypedTextKey"]);

completionHandler();

}

/远程通知的Action按钮被点击后执行 , 与本地通知一样
//-(void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler{
//
//}
//
//

远程通知

当设置action的行为为textInput 就可以调用这个方法,通过responseInfo获取用糊输入的内容,还做其他业务逻辑

//-(void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void (^)())completionHandler{ // //}
//应用程序第一次启动的时候就会调用didFinishLaunchingWithOptions.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UILabel * lab = [[UILabel alloc]initWithFrame:(CGRect){0,100,300,300}];
lab.backgroundColor = [UIColor orangeColor];
lab.numberOfLines = 0; NSLog(@"%@" , [NSString stringWithFormat:@"%@",launchOptions]);
lab.text = [NSString stringWithFormat:@"%@",launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]];
[self.window.rootViewController.view addSubview:lab]; NSLog(@"didFinishLaunchingWithOptions");
if (launchOptions[UIApplicationLaunchOptionsLocalNotificationKey])
{ [self jumpVc]; }


  

推送通知跟NSNotification有所区别:
NSNotification是抽象的,不可见的
推送通知是可见的(能用肉眼看到)

iOS中提供了2种推送通知
本地推送通知(Local Notification)
远程推送通知(Remote Notification)

推送通知有5种不同的呈现效果:
在屏幕顶部显示一块横幅(显示具体内容)
在屏幕中间弹出一个UIAlertView(显示具体内容)
在锁屏界面显示一块横幅(锁屏状态下,显示具体内容)
更新app图标的数字(说明新内容的数量)
播放音效(提醒作用)

如何发送本地通知:

创建本地推送通知对象
UILocalNotification *ln = [[UILocalNotification alloc] init];

设置本地推送通知属性

推送通知的触发时间(何时发出推送通知)
@property(nonatomic,copy) NSDate *fireDate;

推送通知的具体内容
@property(nonatomic,copy) NSString *alertBody;

在锁屏时显示的动作标题(完整标题:“滑动来” + alertAction)
@property(nonatomic,copy) NSString *alertAction;

音效文件名
@property(nonatomic,copy) NSString *soundName;

app图标数字
@property(nonatomic) NSInteger applicationIconBadgeNumber;

调度本地推送通知(调度完毕后,推送通知会在特地时间fireDate发出)
[[UIApplication sharedApplication] scheduleLocalNotification:ln];

获得被调度(定制)的所有本地推送通知
@property(nonatomic,copy) NSArray *scheduledLocalNotifications;

(已经发出且过期的推送通知就算调度结束,会自动从这个数组中移除)

取消调度本地推送通知
- (void)cancelLocalNotification:(UILocalNotification *)notification;

- (void)cancelAllLocalNotifications;

立即发出本地推送通知
- (void)presentLocalNotificationNow:(UILocalNotification *)notification;

本地通知的其他属性:

每隔多久重复发一次推送通知
@property(nonatomic) NSCalendarUnit repeatInterval;

点击推送通知打开app时显示的启动图片
@property(nonatomic,copy) NSString *alertLaunchImage;

附加的额外信息
@property(nonatomic,copy) NSDictionary *userInfo;

时区
@property(nonatomic,copy) NSTimeZone *timeZone;

(一般设置为[NSTimeZone defaultTimeZone] ,跟随手机的时区)

当用户点击本地推送通知,会自动打开app,这里有2种情况
app并没有关闭,一直隐藏在后台
让app进入前台,并会调用AppDelegate的下面方法(并非重新启动app)
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification;

app已经被关闭(进程已死)
启动app,启动完毕会调用AppDelegate的下面方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;

launchOptions参数通过UIApplicationLaunchOptionsLocalNotificationKey取出本地推送通知对象

在iOS 8.0中,如果要使用本地通知,需要得到用户的许可
在didFinishLaunchingWithOptions方法中添加如下代码:

UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];

[application registerUserNotificationSettings:settings];

远程通知是如何操作的:

1.远程通知的操作流程具体是一下几步:

抽象理解: 当服务器要给用户发送通知时, 并且用户没有启动程序, 并处于联网状态, 此时app服务器就把通知内容发送给APNs服务器,再让苹果服务器发送给用户.

详解理解: 当用户登录应用时, 此时通过苹果提供的API 将用户的UDID 和app的boundle ID 通过一种加密算法就行加密,得到一个DeviceToken发送给应用服务器储存在服务器中,当服务器要给用户推送通知时, app服务器是将通知内容以及DeviceToken发送给APNs服务器,苹果通过DeviceToken 将通知推送给用户.(注意,推送远程通知的前提,用户处于联网状态, 这样苹果设备才能与苹果服务器建立长连接, 如果用户使用APP处于前台,此时就不需要通过APNs来进行推送, app服务器就可以直接将通知发送给用户,前提是用户app处于前台)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: