gpt4 book ai didi

ios - 每分钟持续运行 UIButton,即使应用程序最小化

转载 作者:搜寻专家 更新时间:2023-11-01 06:12:17 26 4
gpt4 key购买 nike

当应用程序最小化时,我尝试每分钟运行一次 UIButton。因此,我编写了一个 scheduledTimer 函数来在 Appdelegate 中每 1 分钟运行一次按钮,但它不起作用,错误显示 developeLocationHistoryButton:]: unrecognized selector sent to instance 0x60000024ee80。请给我一些指导。我的代码如下所示。

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

var window: UIWindow?
var backgroundUpdateTask: UIBackgroundTaskIdentifier!
var backgroundTaskTimer: Timer! = Timer()

func doBackgroundTask() {
DispatchQueue.global(qos: .default).async {
self.beginBackgroundTask()
if self.backgroundTaskTimer != nil {
self.backgroundTaskTimer.invalidate()
self.backgroundTaskTimer = nil
}

//Making the app to run in background forever by calling the API
self.backgroundTaskTimer = Timer.scheduledTimer(timeInterval: 60, target:self , selector: #selector(ViewController.HistoryButton(_:)), userInfo: nil, repeats: true)
RunLoop.current.add(self.backgroundTaskTimer, forMode: RunLoopMode.defaultRunLoopMode)
RunLoop.current.run()
self.endBackgroundTask()
}
}
func beginBackgroundTask() {
self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(withName: "test7", expirationHandler: {
self.endBackgroundTask()
})
}
func endBackgroundTask() {
UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
self.backgroundUpdateTask = UIBackgroundTaskInvalid
}

我在ApplicationDidEnterBackground中添加了self.doBackgroundTask(),在ApplicationWillEnterForeground中,我添加了

if self.backgroundTaskTimer != nil {
self.backgroundTaskTimer.invalidate()
self.backgroundTaskTimer = nil

最佳答案

您得到的错误意味着您正试图在一个没有实现它的对象上调用一个方法。你的问题出在这一行

Timer.scheduledTimer(timeInterval: 60, target:self , selector: #selector(ViewController.HistoryButton(_:)), userInfo: nil, repeats: true)

而正是与 target: self, selector: #selector(ViewController.HistoryButton(_:)) 部分。 self 这里是 AppDelegate 的实例,您正在通知计时器调用名为 HistoryButton(_:) 的方法。但是该方法是在 ViewController 类型的对象上定义的——这在选择器中有明确说明。

要解决您的问题,您可以

  1. 实例化 ViewController 并将其作为 target 传递 - 不推荐,因为这容易产生副作用。
  2. 将方法复制到 AppDelegate 并更新您的选择器参数 - 更好,但您重复了代码,如果需要,需要在两个地方更新它。
  3. 将方法提取到外部类并在两个地方(AppDelegateViewController)使用它

关于ios - 每分钟持续运行 UIButton,即使应用程序最小化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53290977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com