二、<iOS 推送> 本地推送

2017-07-25  本文已影响100人  Dosun

最近,再次看路遥 《平凡的世界》时,多多少少有自己的影子在里面,觉得没有什么爱与不爱的,在一起就是一种幸福吧。就像润叶和向前在一起,虽然向前失去了双腿,他最终得到一个好老婆和一个可爱的儿子。有时候觉得和谁在一起真的不重要,重要是她开心,你也觉得幸福。生活应该是柴米油盐,而非风花雪月啦。

一、 iOS 10 本地推送的效果图

本文将重点讲述如何实现 iOS 10的本地推送通知的用法,如下是效果图。

本地推送.gif

上面的 gif 图片都已经本地推送的如下功能:

二、 iOS 10 本地推送实现思路

关于 iOS 10 本地推送实现思路分为如下三个步骤:
0>、手动导入资源文件,如下图。


Snip20170725_34.png

1>、应用启动时,注册通知,并设置 Action 按键的样式和标题。

2>、设置通知的内容,附件、通知的触发条件。

3>、在代理中处理相对应的内容。一般是处理 用户点击那个按键,并处理相对应的事件。

三、 iOS 10 本地代码的实现

1、在 AppDelegate.m 中
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

2>、设置推送的 Action,点击 Action 按键有三种状态,UNNotificationActionOptionForeground 直接开启应用,UNNotificationActionOptionDestructive 取消,
UNNotificationActionOptionAuthenticationRequired 需要解锁


Snip20170725_35.png

3>、将本地推送包装在 UNNotificationCategory 对象中,记得设置 UNNotificationCategory 对象的标识符。

4>、将UNNotificationCategory 对象加入在通知中心去。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    if ([[UIDevice currentDevice].systemVersion doubleValue] >= 10.0) {

        //ios 10 版本以上的通知
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        //注册通知
        [center requestAuthorizationWithOptions:UNAuthorizationOptionBadge| UNAuthorizationOptionSound|UNAuthorizationOptionAlert|UNAuthorizationOptionCarPlay completionHandler:^(BOOL granted, NSError * _Nullable error) {
            NSLog(@"错误的要求通知,%@",error);
            
        }];
        
        // Action 内容 UNNotificationActionOptionForeground 点击 actionbutton 会跳转到应用中
        UNNotificationAction *actionOne = [UNNotificationAction actionWithIdentifier:@"action1" title:@"action1" options:UNNotificationActionOptionForeground];
        
        UNNotificationAction *actionTwo = [UNNotificationAction actionWithIdentifier:@"action2" title:@"action2" options:UNNotificationActionOptionForeground];
        
        UNNotificationAction *actionThree = [UNNotificationAction actionWithIdentifier:@"action3" title:@"action3" options:UNNotificationActionOptionForeground];
        
        //分类
        UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"category" actions:@[actionOne,actionTwo,actionThree] intentIdentifiers:@[] options:0];
        
        //添加分类
        [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObject:category]];
        
        
    }else if([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0){
        //iOS 10 ~ iOS 8 之间的通知
        UIMutableUserNotificationAction *action1 = [UIMutableUserNotificationAction new];
        action1.identifier =  @"actionOne";
        action1.title = @"actionOne";
        action1.activationMode = UIUserNotificationActivationModeForeground;
        
        UIMutableUserNotificationCategory * category = [[UIMutableUserNotificationCategory alloc] init] ;
        
        UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge  categories:[NSSet setWithObject:category]];
 [application registerUserNotificationSettings:setting];
        
    }else if([[UIDevice currentDevice].systemVersion doubleValue] < 8.0){
    
        // 低于 iOS 8 以下的系统
    }
    // Override point for customization after application launch.
    return YES;
}
2、在 ViewController.m 文件中
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
- (void)viewDidLoad {
   [super viewDidLoad];
   [UNUserNotificationCenter currentNotificationCenter].delegate = self;
   // Do any additional setup after loading the view, typically from a nib.
}
  #pragma mark - UNNotification
  //此方法能在前台收到通知
   - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{

    completionHandler(UNNotificationPresentationOptionAlert|UNNotificationPresentationOptionSound);
}

// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
    if ([response.actionIdentifier isEqualToString:@"action1"]) {
        self.noticeImage.image = [UIImage imageNamed:@"1"];
    }else if([response.actionIdentifier isEqualToString:@"action2"]){
        self.noticeImage.image = [UIImage imageNamed:@"2"];
    
    }else if([response.actionIdentifier isEqualToString:@"action3"]){
        UIAlertController *alert =  [UIAlertController alertControllerWithTitle:@"通知标题" message:@"hello world" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"1" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    }
    completionHandler();
}
#pragma  mark - 发送通知
- (IBAction)sendNotice:(id)sender {
    //1.设置通知内容
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = @"通知标题";
    content.subtitle = @"副标题";
    content.body = @"iOS 10 本地通知文本内容,你好吖,亲!!!";
    content.badge = [NSNumber numberWithInteger:1];
    content.categoryIdentifier = @"category";
    content.sound = [UNNotificationSound defaultSound];
    
    //2.设备通知的附件
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"flv视频测试用例1.mp4" withExtension:@""];

    UNNotificationAttachment *attchment = [UNNotificationAttachment attachmentWithIdentifier:@"2" URL:url options:nil error:nil];
    if (attchment == nil) {
        NSLog(@"空的item");
        return;
    }
    content.attachments = @[attchment];
    
    //3.触发本地通知
    UNTimeIntervalNotificationTrigger * trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:2 repeats:NO];
    
    //4.将通知的信息和触发条件放在 request中
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"request" content:content trigger:trigger];
    //5. 添加通知
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        
    }];

}

完整代码,多谢你完整的读完本文,感恩!

上一篇 下一篇

猜你喜欢

热点阅读