【发布时间】: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