用户可以在 slider 中选择几分钟的间隔(3、5、8、10 等)。
因为,无法在自定义时间设置重复的本地通知(仅每秒、分钟、小时、天一次……)。
我创建了一个计时器,可以在选定的时间创建新的本地通知。这里奇怪的是它可以在物理 iPhone 6 和 iPhone 5 模拟器上运行。但在运行 iOS 9.3.2 的实体 iPhone 5 上则不然。
下面是启动计时器的代码,number是从 slider 中获取的整数值(3、5、8...):
@IBAction func saveSettings(sender: AnyObject) {
var timer = NSTimer.scheduledTimerWithTimeInterval(Double(number*60), target: self, selector: Selector("sendNotification"), userInfo: nil, repeats: true)
print("notification interval set to \(number)")
}
func sendNotification() {
let localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow: Double(number))
localNotification.alertBody = "This is a test body."
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
iPhone 5 和 6 之间的某种硬件差异似乎影响了此解决方案。它是什么?我能做些什么来让它同时适用于两者?
最佳答案
您需要创建UILocalNotification
并安排它的所有时间间隔。并设置fireDate
notification.fireDate(YOUR_TIME_INTERVAL)
UIApplication.sharedApplication.scheduleLocalNotification(notification)
类似于您使用 NSTimer 的情况
func sendNotificationNew() -> Void {
let dateTime = NSDate()
var notification = UILocalNotification()
notification.timeZone = NSTimeZone.defaultTimeZone()
notification.fireDate(dateTime)
notification.alertBody("Test")
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
或更改您的代码
@IBAction func saveSettings(sender: AnyObject) {
let dateTime = NSDate().dateWithTimeIntervalSinceNow(Double(number*60))
var notification = UILocalNotification()
notification.timeZone = NSTimeZone.defaultTimeZone()
notification.fireDate(dateTime)
notification.alertBody("Test")
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
关于ios - 使用 NSTimer 的周期性本地通知不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38305763/