2017-02-04 34 views
1

我正在嘗試設置一個函數,該函數將在接下來的n天內接收一個整數並計劃本地通知。我收到一個錯誤,我無法將Date類型轉換爲DateComponents。我一直無法弄清楚如何轉換它。我發現了一些其他類似的問題herehere,但我還沒有能夠適應這些答案在Swift 3上工作。將日期轉換爲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)") 
     } 
    } 
} 

回答

10

我認爲錯誤是明顯的,因爲它可以。 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()) 
+0

謝謝你,這個修正錯誤,是不是我的代碼要簡單得多。我試圖讓它複雜化。 – tylerSF