ios10 UNNtificationRequest UNUserNotificationCenter的应用 推送之本地推送

 iOS10 已经 “deprected” 我们的UILocalNotification 采用了全新的UNUserNotificationCenter;

 1 首先,你需要引进<UserNotifications/UserNotifications.h>

#import <UserNotifications/UserNotifications.h>

  2 然后,在AppDelegate.m中,完成推送通知的注册和请求授权;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 获取通知中心--单例
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    //设置代理
    center.delegate = self;

    //获取用户的推送授权 iOS 10新方法
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                            
                          }];

    //获取当前的通知设置,UNNotificationSettings 是只读对象,readOnly,只能通过以下方法获取
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {

    }];
    return YES;
}

 3 完成注册,之后是通过使用UNUserNotificationCenter 来实现推送通知;

  在要使用本地通知时,通过单例(UNUserNotificationCenter)来实现,通过一个button的点击来启动通知为例:

#pramark mark - 点击按钮发送本地通知事件
- (void) buttonClickAction{

    //  > 使用 UNUserNotificationCenter 来管理通知-- 单例
    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
    
    // > 需创建一个包含待通知内容的 UNMutableNotificationContent 对象,可变    UNNotificationContent        对象,不可变
   //  > 通知内容
    UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
   // > 通知的title
    content.title = [NSString localizedUserNotificationStringForKey:@"推送的标题" arguments:nil];
  // > 通知的要通知内容
    content.body = [NSString localizedUserNotificationStringForKey:@"======推送的消息体======"
                                                         arguments:nil];
    // > 通知的提示声音
    content.sound = [UNNotificationSound defaultSound];
    
    //  > 通知的延时执行
    UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
                                                  triggerWithTimeInterval:5 repeats:NO];
    
    UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
                                                                          content:content trigger:trigger];
    
    //添加推送通知,等待通知即可!
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        
  // > 可在此设置添加后的一些设置
  // > 例如alertVC。。
    }];

}

 

iOS 10 远程推送详见  “ios10   UNNtificationRequest  UNUserNotificationCenter的应用  推送之远程推送”!

 

 

posted @ 2016-10-13 18:16  wangwei_Carry  阅读(4181)  评论(0编辑  收藏  举报