美文网首页
iOS推送通知

iOS推送通知

作者: KouKuma | 来源:发表于2018-06-21 17:25 被阅读10次
    推送通知就是向用户推送一条信息来通知用户某件事情,它可以在APP退到后台或者关闭时仍可推送一条消息告诉用户某件事.

    本地推送通知

    本地即使在不联网的情况下也可以推送消息
    通知发送方: 开发人员负责在APP内发送
    应用场景: 确定知道未来某个时间点提醒用户什么

    远程推送通知

    远程则必须在联网的情况下才能向用户推送消息
    远程推送服务, 又称为 APNs(Apple Push Notification Services)
    通知发送方: 服务器
    应用场景: 不确定未来某个时间点去提醒用户或当APP彻底退出时也想继续让用户获得一些消息

    当发送通知时, 如果当前程序正在前台运行, 那么推送通知就不会被呈现.

    本地通知

    // 发送本地通知
    - (IBAction)sendNotification:(UIButton *)sender
    {
        
        // 请求通知授权
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            
            if (!error)
            {
                NSLog(@"推送授权成功");
            }
            
        }];
        
        // 创建通知内容
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.title = @"推送标题";
        content.subtitle = @"推送副标题";
        content.body = @"这是推送内容,长一点长一点长一点长一点长一点长一点长一点长一点长一点长一点长一点长一点长一点长一点长一点长一点长一点";
        content.badge = @1; // 应用图标提醒数字
        
        // x秒钟后提醒
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];
        
        /**
        //每周日早上十点提醒
        NSDateComponents *components = [[NSDateComponents alloc] init];
        components.weekday = 1;
        components.hour = 10;
        UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];
        */
        
        // 通知标识符
        NSString *requestIdentifier = @"sampleRequest";
        // 创建通知
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier content:content trigger:trigger];
        
        // 发送通知
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            
            if (error) {
                NSLog(@"发送通知错误 %@", error);
            }
            
        }];
        
    }
    
    
    // 查看通知
    - (IBAction)viewNotification:(UIButton *)sender
    {
        // 查看通知设置
        [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            NSLog(@"通知设置: %@",settings);
        }];
    }
    

    iOS10以后通知就使用 UNUserNotificationCenter 这个类, 而不是 UILocalNotification.

    远程通知

    使用极光SDK即可 https://www.jiguang.cn/
    极光的文档 http://docs.jiguang.cn/jpush/client/iOS/ios_sdk/

    相关文章

      网友评论

          本文标题:iOS推送通知

          本文链接:https://www.haomeiwen.com/subject/oahxyftx.html