簡體   English   中英

無法快速向 UserNotifications 添加特定日期和時間

[英]unable to add specific date and time to UserNotifications in swift

我正在從 Datepicker 到文本字段獲取日期和時間.. 我需要設置通知的日期和時間.. 我在應用程序委托中添加了requestAuthorization

通知代碼:我試圖將datepicker日期指定給dateComponents然后yourFireDate時間不正確我的意思是

如果我給出日期和時間8/25/20, 1:03 PM那么 yourFireDate 總是像2020-08-24 18:30:00 +0000一樣來,其余的也不來

 func displayReminderLocalNotification(body: String) {
    
    components = dtPicker.calendar.dateComponents([.day, .month, .year], from: dtPicker.date)
    day = components?.day
     month = components?.month
     year = components?.year
     hrs = components?.hour
    mins = components?.minute
    
    guard let yourFireDate = Calendar.current.date(from: components!) else { return }
    
    print("ihwdeiwqjheiq \(yourFireDate)")
    let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey:
                "Your notification title", arguments: nil)
    content.body = body
    content.categoryIdentifier = "Your notification category"
    content.sound = UNNotificationSound.default
    content.badge = 1

     let dateComponents = Calendar.current.dateComponents(Set(arrayLiteral: Calendar.Component.year, Calendar.Component.month, Calendar.Component.day, Calendar.Component.hour, Calendar.Component.minute), from: yourFireDate)
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
    let request = UNNotificationRequest(identifier: "notification identifier", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

像這樣我正在使用日期選擇器:

 let dateFormatter       = DateFormatter()
  dateFormatter.dateStyle = DateFormatter.Style.short
  dateFormatter.timeStyle = DateFormatter.Style.short
  let strDate = dateFormatter.string(from: dtPicker.date)

   dateLabel.text = strDate

如何設置來自日期選擇器到文本字段的特定日期和時間的通知。 請幫我寫代碼

你的代碼看起來沒問題。

您如何測試通知(提醒)? 如果您只是手動將設備日期更改為所需日期,但與確切時間相差 15 分鍾以上 -> 您將不會看到通知! 嘗試跳到預期通知時間之前的一分鍾,然后移動到下一分鍾(或等待:))。 如果您沒有設置小時/分鍾,這可能會很棘手,因此它會變成 00:00。

此外,如果您想確定,您可以顯式設置DateComponents

var dateComponents = DateComponents()
dateComponents.year = ...
dateComponents.month = ...
dateComponents.day = ...
dateComponents.hour = ...
dateComponents.minute = ...

暫無
暫無

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

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