ios - 使用 NSTimer 的周期性本地通知不起作用

标签 ios iphone swift notifications nstimer

用户可以在 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/

相关文章:

ios - Swift:使 UIScrollView 具有 "going out of focus"效果

ios - 如果 UITableViewController 在 PerformBatchUpdates 完成处理程序中捕获自身,是否会导致保留周期?

ios - 为什么在更改 View 的 id 时不会第二次调用 onAppear()?

ios - 尝试 Apple 的 Sample AVCAM 发现错误

iphone - 测试App Store "Distribution"版本

iphone - 将路由器代码升级到 Alamofire 4.0 和 Swift 3

iphone - Apple Reachability 示例在后台模式下不起作用

ios - EKEvent 的旅行时间

ios - 如何将 CocoaAsyncSocket 库安装到 Swift 中?

ios - Firebase 应用程序邀请在 swift ios 上崩溃