美文网首页
日记类项目 提醒写日记 功能实现

日记类项目 提醒写日记 功能实现

作者: Skysama | 来源:发表于2019-06-19 22:18 被阅读0次

    输出 做了写总结之后才是自己的
    // 注册通知
    Appdelegate 中注册

    #import <UserNotifications/UserNotifications.h>
    
       [self registerAPN];
    
    -(void)registerAPN{
        // ios 10
        if (@available(iOS 10.0, *)) { // iOS10 以上
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
                
            }];
            
        }else{
            
               [self setUserNotifacationSettiings:[UIApplication sharedApplication]];
        }
        
        
    }
    
    
    - (void)setUserNotifacationSettiings:(UIApplication *)application {
        UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
    }
    
    - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
        
        
        
        NSLog(@"接收到了通知== %@== %@",notification.alertBody,notification.alertTitle);
    }
    
    

    使用通知 发送通知 存在userdefaults 中是否打开 开关

    - (void)setnotifactionsWithDate:(NSString*)date{
        
     
        
      NSString *switchstr =  [[NSUserDefaults standardUserDefaults]objectForKey:@"switch"];
        if ([switchstr isEqualToString:@"on"]) {
            [self setLocalnonification:date];
        }
    
    }
    
    - (void)setLocalnonification:(NSString *)date{
        
        if (@available(iOS 10.0, *)) {
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
            // 标题
            content.title = @"该写日记了";
            content.subtitle = @"打开";
            
            NSDateComponents *components = [[NSDateComponents alloc] init];
            // 注意,weekday默认是从周日开始
          
            NSArray *datearray = [date componentsSeparatedByString:@":" ];
            components.hour = [datearray[0] integerValue];
            components.minute = [datearray[1] integerValue];
            
            
            UNCalendarNotificationTrigger *calendarTrigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];
            
            NSString *identifier = @"noticeId";
            UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:calendarTrigger];
            
            [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
                NSLog(@"成功添加推送");
            }];
            
          
            
        
        }else{
        
        
        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        //设置时区(跟随手机的时区)
        localNotification.timeZone = [NSTimeZone defaultTimeZone];
        if (localNotification) {
            localNotification.alertBody = @"该写日记了";
            localNotification.alertAction = @"打开";
            //小图标数字
            localNotification.applicationIconBadgeNumber = 1;
            
            date = [NSString stringWithFormat:@"%@:00",date];
            localNotification.applicationIconBadgeNumber = 0;
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"HH:mm:ss"];
            NSDate *dateda = [formatter dateFromString:date];
            //        [formatter dateFromString:@"22:15:50"];
            //通知发出的时间
            NSLog(@"----%@",dateda);
            localNotification.fireDate = dateda;
            //        [NSDate dateWithTimeIntervalSinceNow:3];
            //        date;
        }
        //循环通知的周期
        localNotification.repeatInterval = kCFCalendarUnitDay;
        
        //设置userinfo方便撤销
        NSDictionary *info = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
        localNotification.userInfo = info;
        //启动任务
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
        
        }
    }
    
    
    

    关闭的时候 在这里我用的是移出所有的通知 因为我在这个项目中只用到了本地写日记提醒这一个通知

    - (void)cancelnotifaction{
    //     移出所有的通知
        if (@available(iOS 10.0, *)) {
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            [center removeAllPendingNotificationRequests];
        }else {
            [[UIApplication sharedApplication] cancelAllLocalNotifications];
        }
        
       
        
    //    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    }
    
    
    - (void)checkUserNotificationEnable { // 判断用户是否允许接收通知
        if (@available(iOS 10.0, *)) {
            __block BOOL isOn = NO;
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                if (settings.notificationCenterSetting == UNNotificationSettingEnabled) {
                    isOn = YES;
                    NSLog(@"打开了通知");
                }else {
                    isOn = NO;
                    NSLog(@"关闭了通知");
                    [self showAlertView];
                }
            }];
        }else {
            if ([[UIApplication sharedApplication] currentUserNotificationSettings].types == UIUserNotificationTypeNone){
                NSLog(@"关闭了通知");
                [self showAlertView];
            }else {
                NSLog(@"打开了通知");
            }
        }
    }
    
    - (void)showAlertView {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"通知" message:@"未获得通知权限,请前去设置" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self goToAppSystemSetting];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
    // 如果用户关闭了接收通知功能,该方法可以跳转到APP设置页面进行修改
    - (void)goToAppSystemSetting {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIApplication *application = [UIApplication sharedApplication];
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([application canOpenURL:url]) {
                if (@available(iOS 10.0, *)) {
                    if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
                        [application openURL:url options:@{} completionHandler:nil];
                    }
                }else {
                    [application openURL:url];
                }
            }
        });
    }
    

    相关文章

      网友评论

          本文标题:日记类项目 提醒写日记 功能实现

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