ios - 从明天开始在 Swift 中安排本地通知每天重复

标签 ios swift uilocalnotification unnotificationtrigger

我正在尝试安排本地通知在特定时间每天触发(即重复),但从明天开始。

即“从明天开始,每天晚上 8 点触发通知”

我一直在使用this SO问题作为指导,我相信我正在做它所说的但我今天运行以下代码时仍然收到通知(例如,如果我在晚上8点之前安排通知):

    func testDateNotification(){

    let content = UNMutableNotificationContent()
    content.title = "Test"
    content.body = "This is a test"
    let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())

    let userCalendar = Calendar.current
    var components = userCalendar.dateComponents([.hour, .minute], from: tomorrow!)

    components.hour = 20
    components.minute = 00


    let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
    let request = UNNotificationRequest(identifier: "test", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request) { (error) in
        if ((error) != nil){
            print("Error \(String(describing: error))")
        }
    }

}

最佳答案

import UserNotifications

  • 检查用户权限
    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) {
    if $0 { } }
    
  • 添加通知
     let fromDate = Date(timeIntervalSince1970: Double(0.0))
    
     let dateComponent = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: fromDate)
    
     let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: true)
     print(trigger.nextTriggerDate() ?? "nil")
    
     let content = UNMutableNotificationContent()
     content.title = "title"
     content.body = "body"
     let request = UNNotificationRequest(identifier: "identify", content: content, trigger: trigger)
     UNUserNotificationCenter.current().add(request) { 
         if let error = $0 {
             print(error)
             return
         }else { 
             print("scheduled") 
         }
     }
    
  • 关于ios - 从明天开始在 Swift 中安排本地通知每天重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44872429/

    相关文章:

    ios - 如何将@noescape 注释添加到可选闭包

    ios - 我们如何在使用表达式值时使用 "context"(使用 :context:)?

    swift - 使用 Realm add()/setValue() 链接 RxSwift 请求

    ios - 子类化 UIView 时初始化器的困惑

    ios - 在 UICollectionViewCell 中使用 UITableView(模仿 Google Places 底部滚动列表)

    swift - 显示来自 watchOS 2 应用程序的通知

    ios - 粘贴到 UISearchController 的 UISearchBar 时启用返回键

    ios - XCUITest,关闭 WebDriverAgent,xcodebuild 退出,代码为 'null'

    ios - 在 UILocalNotification 触发后修改它的最佳方法是什么?

    ios - UILocalNotification 重复间隔不起作用