ios - 手动设置时间和日期时,不会触发 iOS 10 中的重复每日本地通知?

标签 ios swift swift3 nsnotificationcenter

我正在尝试通过触发每日通知来测试 iOS 10 中的本地通知。

我正在使用以下示例项目: NotificationsUI-Demo

在应用程序中是以下代码之一:

let calendar = Calendar(identifier: .gregorian)
    let components = calendar.dateComponents(in: .current, from: date)
    let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)

    let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)

    let content = UNMutableNotificationContent()
    content.title = "Tutorial Reminder"
    content.body = "Just a reminder to read your tutorial over at appcoda.com!"
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "myCategory"

    if let path = Bundle.main.path(forResource: "logo", ofType: "png") {
        let url = URL(fileURLWithPath: path)

        do {
            let attachment = try UNNotificationAttachment(identifier: "logo", url: url, options: nil)
            content.attachments = [attachment]
        } catch {
            print("The attachment was not loaded.")
        }
    }

    let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)

    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().add(request) {(error) in
        if let error = error {
            print("Uh oh! We had an error: \(error)")
        }
    }

let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)

我将 repeats 的值从 false 更改为 true 以每天重复,因为根据描述 repeats参数:

Specify false to unschedule the notification after the trigger fires. Specifying true causes the notification to be rescheduled repeatedly.

假设我触发了今天 4/10/2017 下午 6:56 的通知。下午 6:56,我按预期看到了本地通知。

当我尝试通过“设置”->“日期和时间”将日期和时间手动更改为 4/11/2017 下午 6:55 时,一旦下午 6:56 左右,我根本看不到通知。

难道不能这样测试吗?

我没有试过真的等到第二天的指定时间再弹出通知,但我很好奇为什么这种测试方式不起作用?

谢谢。

最佳答案

您在包含日期和月份的日期 调用repeats。因此,这个日期要到明年才会再次出现。因此,第二天不会发送通知。通知的触发器必须仅包含使用 DateComponents 的小时和分钟值,以允许通知每天重复:

var date = DateComponents()
date.hour = 11
date.minute = 41

let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
let content = UNNotificationContent()

let notification = UNNotificationRequest(identifier: "myNotification", content: content, trigger: trigger)

关于ios - 手动设置时间和日期时,不会触发 iOS 10 中的重复每日本地通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43335557/

相关文章:

ios - 表格 View 单元格重新加载第一个单元格内容

iOS 应用提交 : invalid signature

json - 将 Swift 中的不同 JSON feed 解析为相同的 Decodable 结构

ios - 导航栏中的自定义按钮 - 添加并被点击但不可见

swift - 什么替换了 init(name :float:) now that it has been deprecated

ios - 动态单元格大小

ios - Pickerview 委托(delegate) UIView : array index out of range

xcode - Swift:错误:在类型上使用实例成员

ios - 如何在 Swift 中将 SKScene 覆盖在 SCNScene 上?

ios - swift 3 在应用程序处于后台时读取加速度计数据