【问题标题】:Daily local notification worked for one day and than stopped [Swift]每日本地通知工作了一天,然后停止了 [Swift]
【发布时间】:2020-06-25 15:57:25
【问题描述】:

我为我的应用程序上的每日本地通知编写了一个代码,该通知将在每天下午 1:00 (13:00) 发送。 我写它的那天,代码运行良好,并且通知在下午 1:00 准确发送。 由于未知原因,它仅比现在效果好,但现在不起作用,我没有收到任何通知。

(我在应用的注册页面中编写了代码)

代码:

import UIKit
import FirebaseAuth
import Firebase

class SignUp: UIViewController {

    @IBOutlet weak var emailSignupTF: UITextField!
    @IBOutlet weak var passwordSignupTF: UITextField!
    @IBOutlet weak var errorLabel: UILabel!
    var message = ""

    override func viewDidLoad() {
        super.viewDidLoad()        
        navigationItem.setHidesBackButton(true, animated: true)

        //First Notification//
        let content = UNMutableNotificationContent()
        content.title = "תזכורת"
        content.body = "לא לשכוח לעדכן את מיקומך בתדריך הקרוב"

        // Configure the recurring date.
        var dateComponents = DateComponents()
        dateComponents.calendar = Calendar.current
        dateComponents.hour = 13
        dateComponents.minute = 0


        // Create the trigger as a repeating event.
        let trigger = UNCalendarNotificationTrigger(
                 dateMatching: dateComponents, repeats: true)

        // Create the request
        let uuidString = UUID().uuidString
        let request = UNNotificationRequest(identifier: uuidString,
                    content: content, trigger: trigger)

        // Schedule the request with the system.
        let notificationCenter = UNUserNotificationCenter.current()
        notificationCenter.add(request) { (error) in
           if error != nil {
              // Handle any errors.
           }
        }
}

【问题讨论】:

    标签: swift date notifications nsdatecomponents unusernotification


    【解决方案1】:

    这里的问题是您通过说dateComponents.calendar = Calendar.current 来专门获取今天的日期,然后设置小时和分钟值。这意味着通知将在每年的该日期在指定的小时和分钟发送。要解决此问题,只需执行以下操作:

    // Configure the recurring date.
    var dateComponents = DateComponents()
    dateComponents.hour = 13
    dateComponents.minute = 0
    

    现在通知将在每天 13:00 发送。参考:https://developer.apple.com/documentation/usernotifications/uncalendarnotificationtrigger

    【讨论】:

    • 这不行吗?建设性的批评会有所帮助:)
    • 很奇怪。这个对我有用。你如何测试它?我在手机上运行它,并手动更改了时间。每次 13:00 都会收到通知,即使更改为其他日期。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 2014-02-22
    • 2020-01-11
    • 2016-06-04
    • 2016-05-18
    • 1970-01-01
    相关资源
    最近更新 更多