我有以下函数 setPath()
每当用户点击按钮时调用该函数:
var loadSuccessfulTimer: Timer? = nil
func setPath(index: Int) {
self.loadSuccessfulTimer?.invalidate()
self.loadSuccessfulTimer = nil
print("setting path")
self.pause(releaseAudioSession: false)
self.reset(index: index)
let song = DataManager.getInstance().getQueueSong(index: index)
superpowered.setPath(song.url, true)
self.loadSuccessfulTimer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(checkLoadSucess), userInfo: nil, repeats: true)
self.loadSuccessfulTimer!.fire()
}
@objc func checkLoadSucess() {
let status = self.superpowered.getLoadSuccessful()
print(status)
if(status != -1) {
self.loadSuccessfulTimer?.invalidate()
self.loadSuccessfulTimer = nil
if(status == 1){
print("success")
} else if(status == 2){
print("failed")
}
}
}
因此,每当调用 setPath()
函数时,我希望计时器每 0.2
秒触发一次,以检查 status = self 的值。 superpowered.getLoadSuccessful()
。变量 status 的值为 -1, 1, 2
我想在它为 1
或 2
时停止计时器。然而,下面的场景正在发生:
在第一次点击时它按预期工作并打印以下内容:
setting path
-1
-1
-1
-1
-1
-1
1
success
在第二次点击时,计时器只被触发一次(我猜它来自 .fire()
)并且正在打印以下内容:
setting path
-1
我试图查找可能出了什么问题,但我只能看到这是使用 Timer
的推荐方式。
更新
第二次 setPath()
被 DispatchQueue.global()
调用,可能与问题有关。
最佳答案
NSTimer 需要运行循环才能正常工作。主队列有一个免费的运行循环,对于其他队列,您需要确保运行循环可用。
请务必阅读文档:https://developer.apple.com/documentation/foundation/nstimer
此外,请记住从创建(调度)的同一运行循环(线程)中使 NSTimer 对象无效。
关于ios - NSTimer 在无效和重新初始化后仅被触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51050929/