2017-10-23 5 views
-1

UNCalendarNotificationTriggerとすると、毎日特定の時間に繰り返すことができます。 UNTimeIntervalNotificationTrigger時間ごとにX時間ごとにプッシュ通知を繰り返します。

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

私はそれは、タイマーを作成したときから、いくつかの間隔で繰り返すように取得することができます。

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: Double(frequency*60), repeats: true)

どのようにかかわらず、私はいくつかの柔軟な間隔で、時間に繰り返すようにプッシュ通知を得ることができますか?たとえば、午前12時から、2時間ごと、3時間ごと、または12時間ごとなどとなります。

答えて

0

あなたは、毎日特定の時間を繰り返し設定できることが分かっている場合は、間隔に基づいて時間を計算してみませんか?

var components = DateComponents() 
components.hour = 5 
components.second = 0 

let interval: Double = 60 * 30 // 30 min 
let maxDuration: Double = 60 * 60 * 5 // 5 hours 
let startDate = Calendar.current.date(
    byAdding: components, 
    to: Calendar.current.startOfDay(for: Date())) 
let endDate = startDate.addingTimeInterval(maxDuration) 

let notificationCount: Int = Int((endDate.timeIntervalSince1970 - startDate.timeIntervalSince1970)/maxDuration) 

(0..<notificationCount) 
    .map({ startDate.addingTimeInterval(Double($0) * interval) }) 
    .forEach({ date in 
     // Schedule notification for each date here 
    }) 

範囲と1日の重複を管理する必要がありますが、これは正しい方向を指しているはずです。

関連する問題