swift - UNUserNotificationCenter.getNotificationSettings 中的计时器失败
问题描述
我正在尝试根据应用程序是否提供推送权限在视图控制器上启动一些计时器,但计时器没有触发。谁能向我解释为什么会这样?
class SomeViewController: UIViewController {
private var startTime: Date!
private var countDown: Timer?
private var timer: Timer?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
startTime = Date()
UNUserNotificationCenter.current().getNotificationSettings { settings in
if settings.authorizationStatus == .denied || settings.authorizationStatus == .notDetermined {
self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.manualFunction(_:)), userInfo: nil, repeats: true)
} else {
// Wait two seconds, then start the manual check.
self.countDown = Timer.scheduledTimer(withTimeInterval: 2, repeats: false, block: { (timer) in
self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.manualFunction(_:)), userInfo: nil, repeats: true)
})
}
}
}
@objc private func manualFunction(_ timer: Timer) {
// Some function I want to execute whenever the second timer triggers.
}
}
该viewDidAppear
函数用于包含以下确实有效的代码:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
startTime = Date()
self.countDown = Timer.scheduledTimer(withTimeInterval: 2, repeats: false, block: { [weak self] (timer) in
guard let self = self else { return }
self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.manualFunction(_:)), userInfo: nil, repeats: true)
})
}
我试过制作计时器weak
,我试过在几个地方添加[unowned self]
和,但没有成功。[weak self]
有人可以解释这种行为吗?
解决方案
调用该getNotificationSettings
方法时,您将进入后台队列,您应该返回主队列来处理要在主队列中执行的任务。
UNUserNotificationCenter.current().getNotificationSettings { settings in
DispatchQueue.main.async {
// Add your tasks here
}
}
推荐阅读
- audio - 低延迟的FFmpeg实时音频流
- python - 子进程 for 循环失败并出现语法错误
- javascript - Angular Webpack 设置:使用 webpack 从 css 迁移到 sass
- java - android中的CursorIndexOutOfBoundException index 0 size 0
- excel - 粘贴 Excel 图表
- java - 如何比较时间戳是否在Java中的给定时间段范围内
- cmd - 通过cmd和时间戳备份删除window中的子文件夹和文件
- python - 实现双链表 - 调用头节点时的最大递归深度
- android - 如何摆脱 AppBarLayout 和 TabLayout 之间的阴影?
- django - django 中默认身份验证视图的表单操作和没有反向匹配