后台根据时间激活本地通知

2024-04-17

因此,我有一个包含重复间隔本地通知的应用程序,我想添加一个在睡眠期间暂停通知的功能。

到目前为止,我已经为用户创建了两个日期选择器,以指定他们想要停止重复间隔的时间以及自动重新启动的时间。我还为他们添加了一个 uiswitch 来激活睡眠模式或忽略该功能。

现在,我将如何让我的主 uipickerview -(他们从这里选择通知) - 监听 uiswitch(如果它已打开),然后它会在来自我的第一个日期选择器的时间暂停通知,并在来自第二个日期选择器的时间?

我已经设置了我的 datepickers 和我的 uiswitch 但不知道如何用我的 uipickerview 实现它。它应该在 DidSelectRow 的方法下吗?或者 appdelegate 中的方法(如 DidEnterBackground)?

请询问您是否需要更多信息或代码来理解这个想法并帮助我。谢谢。

ADD ON:

这是我为日期选择器准备的代码,但是,我只是缺少将其正确添加到我的选择器视图的连接。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.timeZone=[NSTimeZone defaultTimeZone];
dateFormatter.timeStyle=NSDateFormatterShortStyle;
dateFormatter.dateStyle=NSDateFormatterShortStyle;
NSString *dateTimeString=[dateFormatter stringFromDate:startTime.date];
NSLog(@"Start time is %@",dateTimeString);


NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
dateFormatter2.timeZone=[NSTimeZone defaultTimeZone];
dateFormatter2.timeStyle=NSDateFormatterShortStyle;
dateFormatter2.dateStyle=NSDateFormatterShortStyle;
NSString *dateTimeString2=[dateFormatter2 stringFromDate:endTime.date];
NSLog(@"End time is %@",dateTimeString2);

我还有这段代码可以在不同时间之间进行比较:

if ([[NSDate date] isEqualToDate:startTime.date]) {
NSLog(@"currentDate is equal to startTime"); 
}

if ([[NSDate date] isEqualToDate:endTime.date]) {
NSLog(@"currentDate is equal to endTime"); 
}

iOS 不支持在两个特定日期/时间之间发布本地重复通知。此外,与基于地理的通知不同,应用程序不在前台时不会收到触发通知的警报。因此,我们需要通过在用户不睡觉时创建许多单独的通知来解决这个问题。

请按照以下步骤创建基本解决方案:

  1. 将您的控件连接到视图控制器标头中的 IBOutlet:

    SomeViewController.h:

    @interface SomeViewController : UIViewController
    
    @property (weak, nonatomic) IBOutlet UISwitch *sleepToggleSwitch;
    @property (weak, nonatomic) IBOutlet UIDatePicker *notificationIgnoreStartTime;
    @property (weak, nonatomic) IBOutlet UIDatePicker *notificationIgnoreEndTime;
    @property (weak, nonatomic) IBOutlet UIPickerView *notificationTypePickerView;
    
    @end
    
  2. 创建 IBAction 方法并连接视图控制器实现文件中的每个控件(两个 UIDatePicker、一个 UISwitch 和一个 UIPickerView)。每个方法都应该调用私有方法startUserOptionInteractionTimer.

    SomeViewController.m:

    - (IBAction)noNotificationPeriodStartDateChanged:(id)sender
    {
        [self startUserOptionInteractionTimer];
    }
    
    - (IBAction)noNotificationPeriodEndDateChanged:(id)sender
    {
        [self startUserOptionInteractionTimer];
    }
    
    - (IBAction)sleepToggleSwitchToggled:(id)sender
    {
        [self startUserOptionInteractionTimer];
    }
    
    - (IBAction)notificationTypeChanged:(id)sender
    {
        [self startUserOptionInteractionTimer];
    }
    
  3. In the startUserOptionInteractionTimer私有方法,我们(重新)启动一个 NSTimer。我们在这里使用计时器,这样如果用户更改日期或快速切换开关(他们很可能会这样做),您就不会连续快速地拆卸和设置通知。 (NSTimer 属性userOptionInteractionTimer应在实现文件的接口延续中声明)。

    SomeViewController.m:

    - (void)startUserOptionInteractionTimer
    {
        // Remove any existing timer
        [self.userOptionInteractionTimer invalidate];
        self.userOptionInteractionTimer = [NSTimer scheduledTimerWithTimeInterval:4.f
                                                                           target:self
                                                                         selector:@selector(setupNotifications)
                                                                         userInfo:nil
                                                                          repeats:NO];
    }
    
  4. 创建另一个私有方法来拆除预先存在的通知并设置新的通知。

    此处设置通知取决于您想要通知用户的时间和频率。假设您希望每小时通知一次用户,并且用户启用了睡眠功能,那么您将每小时设置 14-18 条通知(取决于用户睡眠的时间),每天重复一次。

    SomeViewController.m:

    - (void)setupNotifications
    {
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
        // Read the notification type from the notification type picker view
        NSInteger row = [self.notificationTypePickerView selectedRowInComponent:0]; // Assumes there is only one component in the picker view.
        NSString *notificationType = [self.notificationList objectAtIndex:row]; // Where notificationList is the array storing the list of notification strings that appear in the picker view.
    
        // If the user has turned the sleep feature on (via the UISwitch):
        if (self.sleepToggleSwitch.on) {
            // Set the first notification to start after the user selected 'noNotificationPeriodEndDate' and repeat daily.
            // Add 1 hour to the notification date
            // Do while the notification date < the user selected 'noNotificationPeriodStartDate' ...
            //     Create the notification and set to repeat daily
            //     Add 1 hour to the notification date
            // Loop
        } else {
            // Set up 24 repeating daily notifications each one hour apart.
        }
    }
    

    请记住,单个应用程序最多只能创建 64 个通知(重复的通知算作一个),因此,如果您希望通知在几天或几周内的不同时间触发,您可能需要重新考虑您的设计小的。

  5. 在 NSUserDefaults 中加载并存储用户选择的首选项:

    SomeViewController.m:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        // Load the user defaults
        NSDate *sleepStartDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"SleepStartDate"];
        self.notificationIgnoreStartTime.date = sleepStartDate ? sleepStartDate : [NSDate date];
        NSDate *sleepEndDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"SleepEndDate"];
        self.notificationIgnoreEndTime.date = sleepEndDate ? sleepEndDate : [NSDate date];
        self.sleepToggleSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"SleepEnabled"];
    
        // Watch for when the app leaves the foreground
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(applicationWillResignActive)
                                                     name:UIApplicationWillResignActiveNotification object:nil];
    }
    
    - (void)applicationWillResignActive
    {
        // If the timer is still waiting, fire it so the notifications are setup correctly before the app enters the background.
        if (self.userOptionInteractionTimer.isValid)
            [self.userOptionInteractionTimer fire];
    
        // Store the user's selections in NSUserDefaults
        [[NSUserDefaults standardUserDefaults] setObject:self.notificationIgnoreStartTime.date forKey:@"SleepStartDate"];
        [[NSUserDefaults standardUserDefaults] setObject:self.notificationIgnoreEndTime.date forKey:@"SleepEndDate"];
        [[NSUserDefaults standardUserDefaults] setBool:self.sleepToggleSwitch.on forKey:@"SleepEnabled"];
    }
    

    另外,请注意上面的内容,如果应用程序即将进入后台(即离开前台)并且计时器仍在滴答作响,我们会强制它触发,以便在计时器被操作系统终止之前设置通知。

  6. 请记住连接所有日期选择器视图的委托 IBActions 和所有 IBActions 以及选择器视图的委托和数据源。另请记住设置委托和数据源方法,以便填充选择器视图。

  7. 就是这样!

上述设计将确保通知在正确的时间触发,无论应用程序是否处于前台、后台或终止状态。 (但是,如果收到通知时应用程序位于前台,则用户将不会收到通知。相反,application:didReceiveLocalNotification:appDelegate 上将被调用)。

显然,上面的代码还没有“执行就绪”,但您应该能够填补空白。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

后台根据时间激活本地通知 的相关文章

随机推荐

  • 如何设置文本字段字符限制 SwiftUI?

    我正在使用 SwiftUi 版本 2 进行应用程序开发 我遇到了 SwiftUI 中可用文本字段的问题 我不想再使用 UITextField 了 我想限制文本字段中的字符数 我搜索了很多 找到了一些与此相关的答案 但这些答案不适用于 Swi
  • Docker:基础镜像

    我试图理解 Docker 概念 但我无法理解一件事 据我了解 镜像 即容器 可以从不同的 Linux 发行版实例化 例如 Ubuntu CentOS 等 假设我在主机上运行标准 Ubuntu 14 04 What happens if I
  • 卷曲总是返回 false

    下面的代码总是回显 false 我错过了什么吗 url https www google nl ch curl init curl setopt ch CURLOPT URL url curl setopt ch CURLOPT RETUR
  • 找不到如何使用 HttpContent

    我正在尝试使用HttpContent HttpContent myContent HttpContent Create SOME JSON 但我没有找到定义它的 DLL 首先 我尝试添加对Microsoft Http也System Net
  • Scrapy 使用带有规则的 start_requests

    我找不到任何使用 start requests 与规则的解决方案 我也没有在互联网上看到任何关于这两个的示例 我的目的很简单 我想重新定义 start request 函数以获得捕获请求期间所有异常的能力 并在请求中使用元 这是我的蜘蛛的代
  • 结果在同一个文件夹中

    我尝试执行以下命令来对文件夹内找到的数据进行分析 但是 它将它们保存在我执行该行的文件夹中 如何将结果保存在文件所在的文件夹中位于 sed n 14 71p fastqc fastqc txt awk print 1 2 awk sum 2
  • 如何在golang中$push嵌套数组?

    我尝试使用以下方法将一些数据推送到嵌套数组中 push 这是我的 json 文件 id ObjectId 57307906f051147d5317984e user firstName chetan lastName kumar age 2
  • Composer PSR-4 自动加载“找不到类”调试

    是的 另一个关于 找不到类 错误的问题 要么是我遗漏了什么 要么是我误解了 PSR 4 逻辑 我的作曲家库目录结构 扫描仪 gt src gt Test php Test php namespace MyNS class Test 作曲家
  • firebase 的 addValueEventListener() 和 addListenerForSingleValueEvent() 之间的区别

    正如标题所说 我想知道两者之间的区别addValueEventListener and addListenerForSingleValueEvent Firebase 的 addValueEventListener 继续侦听其附加的查询或数
  • 从类定义中省略“private”关键字是否会造成混淆?

    我最近删除了一个private从类定义中指定 因为它位于顶部 紧接在class关键词 class MyClass private int someVariable 我认为这是多余的 一位同事不同意这一点 称这实际上 隐藏 了private数
  • 加载linux内核的基地址

    我对内核如何加载到内存有一些疑问 检查后 proc kallsyms我能够找到内核中各种符号的地址 cat proc kallsyms head n 10 00000000 t vectors start 80008240 T asm do
  • SQL 数据类型 - 如何存储年份?

    我需要在数据库中插入年份 例如 1988 1990 等 当我使用日期或日期时间时 数据类型 它显示错误 我应该使用哪种数据类型 常规的 4 字节 INT 太大了 浪费空间 您没有说明您正在使用什么数据库 因此我无法推荐特定的数据类型 每个人
  • 如何在 d3 力定向图中突出显示(更改颜色)所有连接(邻居)节点和链接

    我在这里看到了这个例子http www d3noob org 2013 03 d3js force directed graph example basic html http www d3noob org 2013 03 d3js for
  • Kotlin 中的驱逐队列

    我需要一个集合 有固定的大小 是可变的 添加新元素后将重新索引元素 删除最旧的元素 如移位寄存器 我觉得番石榴EvictingQueue https guava dev releases 15 0 api docs com google c
  • 有没有办法将色调仅应用于seaborn中PairGrid的下部

    我想知道是否可以将色调仅应用于seaborn的下部PairGrid For example say I have the following figure 对于我需要展示的内容 我想将密度图保留在对角线上 将整体散点图保留在上部 在其上方打
  • 连接 Apollo 和 mongodb

    我想将我的 Apollo 服务器与我的 mongoDB 连接 我知道那里有很多例子 但我陷入了异步部分 没有找到解决方案或示例 这很奇怪 我完全错了吗 我从 next js 的示例开始https github com zeit next j
  • “窗口”类型不支持直接内容

    我有一个使用 VS 2015 构建的 WPF 解决方案 由多个项目组成 突然 我开始在设计模式下收到一条警告 内容如下 窗口 类型不支持直接内容 我了解某些控件不支持直接内容 但是System Windows Window应该 我收到同样的
  • Android 编程错误

    我正在使用 Eclipse Galileo 编写 Android 你好 测试 教程 http developer android com resources tutorials testing helloandroid test html
  • ASP.net 页面在导入语句上出现错误,但我确实有引用吗?

    任何想法为什么我在我的 MVC2 项目中收到以下错误 即使在项目本身中我肯定有对 system Web Entity 的引用 Compiler Error Message CS0234 The type or namespace name
  • 后台根据时间激活本地通知

    因此 我有一个包含重复间隔本地通知的应用程序 我想添加一个在睡眠期间暂停通知的功能 到目前为止 我已经为用户创建了两个日期选择器 以指定他们想要停止重复间隔的时间以及自动重新启动的时间 我还为他们添加了一个 uiswitch 来激活睡眠模式