簡體   English   中英

Swift 4重復本地通知

[英]Swift 4 Repeating Local Notifications

我正在嘗試發出一條將在每天的同一時間(7:00 AM)觸發的通知。 如果我使用UNTimeIntervalNotificationTrigger而不是UNCalendarNotificationTrigger ,那我就能得到要觸發的通知,這正是我真正想要的。 這是我目前擁有的:

在AppDelegate.swift中,我有:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (didAllow, error) in
        if error != nil {
            print(error as Any)
        }
    }

    return true
}

我記得也要導入UserNotifications

當用戶按下ViewController.swift中的按鈕時,將運行該命令:

let content = UNMutableNotificationContent()
    content.title = "Do your daily review"
    content.badge = 1

    let triggerTime = DateComponents.init(hour: 7, minute: 0, second: 0)
    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerTime, repeats: true)

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

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil

您能否向我解釋一下這里出了什么問題,為什么UNTimeIntervalNotificationTrigger可以工作,而UNCalendarNotificationTrigger卻不起作用?

我不確定它是否可以解決您的問題,但您是直接從init設置DateComponent。 我建議您通過初始化一個空的DateComponent並僅根據需要設置小時來做到這一點。

因此,您可以嘗試執行以下操作:

let content = UNMutableNotificationContent()
content.title = "Do your daily review"
content.badge = 1

var triggerTime = DateComponents()
triggerTime.hour = 7

let trigger = UNCalendarNotificationTrigger(dateMatching: triggerTime, repeats: true)

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

UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

我從自己的角度做到了,並且有效。

希望對您有所幫助。

我的原始代碼運行良好,只需要以不同的方式進行測試即可。 出於某種原因,如果我將代碼中的時間設置為7:00 AM,然后在Mac上模擬該時間,則該時間不起作用,但是如果我將其設置為實時時間+ 1分鍾,並且我等待了一分鍾,卻沒有改變計算機的時間,它可以正常工作。 也許Apple會在時間跳變后立即停止通知,以防止人們在更改時區時遇到通知問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM