2017-02-04 5 views
1

整数をとり、今後n日以内にローカル通知をスケジュールする機能をセットアップしようとしています。私は型DateをDateComponentsに変換できないというエラーが発生しています。私はそれを変換する方法を見つけることができませんでした。他の同様の質問herehereが見つかりましたが、私はこれらの答えをSwift 3で動かすことができませんでした。Swift 3でローカル通知をスケジュールする機能でDate to DateComponentsを変換する

DateをDateComponentsに変換するにはどうすればよいですか?通知をスケジュールするより良い方法はありますか?助けを事前に

感謝:)

エラーのある行は、「型の値に変換できません 『日?』

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

のフル機能:「予想引数の型 'DateComponents' に

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

関連する問題