gpt4 book ai didi

ios - 在 Swift 中,当应用程序进入后台时,如何在 AppDelegate 中验证 NSTimer?

转载 作者:可可西里 更新时间:2023-10-31 23:45:10 27 4
gpt4 key购买 nike

我需要将我的 iOS 应用程序从 obj-c 转换为 swift。我在 ViewController 中有一个 NStimer,它每 30 秒从 shoutcast 加载一次元数据,但是当应用程序退出事件时它会停止,当进入前台时它会再次运行。

编辑:好的。问题解决了!我在 viewDidLoad 中添加了两个名为 UIApplicationWillResignActiveNotificationUIApplicationWillEnterForegroundNotification 的观察者,如下所示:

override func viewDidLoad() {
NSLog("System Version is \(UIDevice.currentDevice().systemVersion)");
super.viewDidLoad()
self.runTimer()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "invalidateTimer", name: UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "runTimer", name: UIApplicationWillEnterForegroundNotification, object: nil)
}

我做了两个函数。第一个用于运行计时器:

func runTimer(){
loadMetadata()
myTimer.invalidate()
NSLog("timer run");
myTimer = NSTimer.scheduledTimerWithTimeInterval(30.0, target: self, selector: "loadMetadata", userInfo: nil, repeats: true)
let mainLoop = NSRunLoop.mainRunLoop()
mainLoop.addTimer(myTimer, forMode: NSDefaultRunLoopMode)
}

然后停止它:

func invalidateTimer(){
myTimer.invalidate()
NSLog("timer invalidated %u", myTimer);
}

我希望这可以帮助某人。 :)

最佳答案

我建议您使用适合您任务的系统:https://developer.apple.com/library/ios/documentation/iphone/conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH4-SW56

Apps that need to check for new content periodically can ask the system to wake them up so that they can initiate a fetch operation for that content. To support this mode, enable the Background fetch option from the Background modes section of the Capabilities tab in your Xcode project. (You can also enable this support by including the UIBackgroundModes key with the fetch value in your app’s Info.plist file.)...

When a good opportunity arises, the system wakes or launches your app into the background and calls the app delegate’s application:performFetchWithCompletionHandler: method. Use that method to check for new content and initiate a download operation if content is available.

关于ios - 在 Swift 中,当应用程序进入后台时,如何在 AppDelegate 中验证 NSTimer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26563921/

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