1

尽管在这段代码上花费了几天的时间,但我仍然无法让它按应有的方式触发。在线查看了许多最近的教程,我的代码与它们全部匹配,但在构建到模拟器或设备时仍然不能正常运行。我想要的只是每天在特定时间触发的本地通知(显示的代码在上午 10:12 尝试)。部署目标是 iOS 14.3,我使用的是最新的 swift 5。绝望中我什至尝试使用时间间隔 UNTimeIntervalNotificaitonTrigger 方法来创建到第二天的时间跨度,但这在设备和模拟器上的测试非常零星(有时会触发秒或分钟)但是,理想情况下,我希望它每天在特定时间触发。

我没有在 appDelegate 或 sceneDelegate 中编写任何代码,因为我遵循的教程根本没有。所有这些代码都是我希望从中授权通知的 ViewController 的 viewDidLoad(如果有区别,这不是初始视图控制器)。求救!

        //STEP 1 - Ask user for permission to notify
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
            if success {
                // TO REMOVE NOTIFICAITONS: UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
                print("All set with User Authorisation!")
            } else if let error = error {
                print("Oh No, Authorisation did not work: ", error.localizedDescription)
            }
        }
        
        //STEP 2 - Create Notification Content
        let content = UNMutableNotificationContent()
        content.title = "Daily Notification TITLE"
        content.subtitle = "Hey - this is your daily notification SUBTITLE"
        content.body = "This is the BODY of your daily notification"
        content.sound = UNNotificationSound.default
        
        
        //STEP 3 - Set up the Trigger by time each day
        var triggerTime = DateComponents()
        triggerTime.hour = 10
        triggerTime.minute = 12
        let myNotificationTrigger = UNCalendarNotificationTrigger(dateMatching: triggerTime, repeats: true)

        // STEP 4 - Creating the Request
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: myNotificationTrigger)

        // Step 5 - Register the Request
        UNUserNotificationCenter.current().add(request) { (error) in
            if let error = error{
                print("Error has occured: \(error.localizedDescription)")
            } else {
                print("Added Notification: \(UUID().uuidString)")
            }
        }
        
    } // END OF THE viewDidLoad bracket
4

0 回答 0