【问题标题】:UNUserNotification is sending notification instantly in iosUNUserNotification 正在 ios 中立即发送通知
【发布时间】:2016-12-21 06:56:10
【问题描述】:

我想在应用程序进入后台后每隔 60 秒发送一次通知。但是当你进入后台时,通知会立即发送,之后每 60 秒发送一次通知。我不想立即发送通知,我该怎么做?

这是我的代码,

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
        // Enable or disable features based on authorization.
    }
    return true
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey: "Hello,", arguments: nil)
    content.body = NSString.localizedUserNotificationString(forKey: "Some", arguments: nil)
    content.sound = UNNotificationSound.default()
    content.badge = NSNumber(value: UIApplication.shared.applicationIconBadgeNumber + 1)
    content.categoryIdentifier = "com.mahmut.localNotification"

    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60.0, repeats: true)
    let request = UNNotificationRequest.init(identifier: "60Sec", content: content, trigger: trigger)

    let center = UNUserNotificationCenter.current()
    center.add(request)

}

【问题讨论】:

  • 在我看来,您可以在应用程序进入后台 60s 后使用 dispatch_after 添加您的 UNNotificationRequest。
  • 调度并没有真正起作用。我将代码放入 DispatchQueue.main.asyncAfter(deadline: .now() + 60.0) { } 通知在 4 秒后发送,有时是 40 秒。
  • 我试过你的代码,它似乎工作正常

标签: ios swift notifications local


【解决方案1】:

尝试以这种方式使用它...而不是 4,您可以使用自己的时间...稍后在您的函数中,您可以使用计时器概念每 60​​ 秒发送一次通知。

    let triggerTime = (Int64(NSEC_PER_SEC) * 4)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
        self.callYourFunction() 
    })

【讨论】:

  • 嗨,我正在使用 swift3,我尝试了 DispatchQueue.main.asyncAfter(deadline: .now() + 60.0) { self.myfunction},但没有成功。
  • 我在 swift 2.3 中使用过这个......我的场景是我使用了这个 viewDidLoad 函数。我想延迟一个获取当前位置坐标的特定函数。由于模拟器没有位置..我曾经在4秒之前模拟一个位置。稍后我必须每 10 秒更新一次坐标并为此使用计时器概念
  • 我不确定它是否正是 swift 3 中的代码,但您是否尝试过确切的代码??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 2017-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多