簡體   English   中英

將Date轉換為DateComponents函數以在Swift 3中安排本地通知

[英]Convert Date to DateComponents in function to schedule local notification in Swift 3

我正在嘗試設置一個接收整數的函數,並在將來的n天內安排本地通知。 我收到一個錯誤,我無法將類型Date轉換為DateComponents。 我無法弄清楚如何轉換它。 我在這里這里找到了一些其他類似的問題,但我無法使這些答案適應Swift 3的工作。

如何將Date轉換為DateComponents? 有沒有更好的方法來安排通知?

在此先感謝您的幫助 :)

帶有錯誤的行,“無法轉換類型'日期的值?' 預期的參數類型'DateComponents'“:

let trigger = UNCalendarNotificationTrigger(dateMatching: fireDateOfNotification, repeats: false)

功能齊全:

func scheduleNotification(day:Int) {    
    let date = Date()
    let calendar = Calendar.current
    var components = calendar.dateComponents([.day, .month, .year], from: date as Date)
    let tempDate = calendar.date(from: components)
    var comps = DateComponents()

    //set future day variable
    comps.day = day

    //set date to fire alert
    let fireDateOfNotification = calendar.date(byAdding: comps as DateComponents, to: tempDate!)

    let trigger = UNCalendarNotificationTrigger(dateMatching: fireDateOfNotification, repeats: false) //THIS LINE CAUSES ERROR

    let content = UNMutableNotificationContent()
    content.title = "New Alert Title"
    content.body = "Body of alert"
    content.sound = UNNotificationSound.default()

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

    UNUserNotificationCenter.current().add(request) {(error) in
        if let error = error {
            print("Uh oh! We had an error: \(error)")
        }
    }
 }

我認為錯誤是盡可能清楚的。 UNCalendarNotificationTrigger是靈活的,因此您可以指定“在下周五觸發觸發器”。 您需要的只是將下一個觸發日轉換為DateComponents

let n = 7
let nextTriggerDate = Calendar.current.date(byAdding: .day, value: n, to: Date())!
let comps = Calendar.current.dateComponents([.year, .month, .day], from: nextTriggerDate)

let trigger = UNCalendarNotificationTrigger(dateMatching: comps, repeats: false)
print(trigger.nextTriggerDate())

暫無
暫無

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

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