任何人要做到這一點斯威夫特,你可以做這樣的事情:
func scheduleNotfications() {
print("Scheduling reminder notifications")
UIApplication.sharedApplication().cancelAllLocalNotifications()
let windowInSeconds: UInt32 = 60*60*5
let oneDayInSeconds: Double = 60*60*24
let windowAroundHour = 14
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
calendar?.timeZone = NSTimeZone.localTimeZone()
if let todayAtWindowHour = calendar?.dateBySettingHour(windowAroundHour, minute: 0, second: 0, ofDate: NSDate(), options: .MatchFirst)?.timeIntervalSinceReferenceDate {
for index in 1...48 {
var notificationDate = (todayAtWindowHour + (Double(index) * oneDayInSeconds))
// either remove or add anything up to the window
if arc4random_uniform(2) == 0 {
notificationDate = notificationDate + Double(arc4random_uniform(windowInSeconds))
} else {
notificationDate = notificationDate - Double(arc4random_uniform(windowInSeconds))
}
let fireDate = NSDate(timeIntervalSinceReferenceDate: notificationDate)
let notification = UILocalNotification()
notification.alertBody = NSLocalizedString("You've received a new notification.", comment: "Notification")
notification.fireDate = fireDate
notification.timeZone = NSTimeZone.defaultTimeZone()
notification.applicationIconBadgeNumber = 1
UIApplication.sharedApplication().scheduleLocalNotification(notification)
print("Set for: \(fireDate)")
}
}
print("Finished scheduling reminder notifications")
}
以上將安排隨機通知在接下來的48天,確保這些通知只能在一天中合理的時間開火。
您可以從applicationDidBecomeActive稱之爲()
func applicationDidBecomeActive(application: UIApplication) {
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
scheduleNotfications()
}
localNotification.repeatInterval = NSDayCalendarUnit;這條線每天都會觸發本地通知在同一時間,但我想在隨機時間 –