繁体   English   中英

从后台返回后,定时器循环偶尔会崩溃

[英]Timer Loop crashes sporadically after returning from the background

我在最新的应用程序版本中遇到了一致的问题。 我有一个在AppDelegate中运行的计时器,它每隔30秒调用一个函数来加载一个新的广告。 我认为这是这场车祸的罪魁祸首。 使用Crittercism,我有13个用户超过20次崩溃。 用户大多使用IOS 6或其中的一些变体。 这是它给我的日志:

SEGV_ACCERR

0 libobjc.A.dylib 0x3acd25b0 objc_msgSend + 16

1基金会0x3394b277 __NSFireDelayedPerform + 451

2 CoreFoundation 0x330125df CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION + 15

3 CoreFoundation 0x33012291 __CFRunLoopDoTimer + 273

4 CoreFoundation 0x33010f01 __CFRunLoopRun + 1233

5 CoreFoundation 0x32f83ebd CFRunLoopRunSpecific + 357

6 CoreFoundation 0x32f83d49 CFRunLoopRunInMode + 105

7 GraphicsServices 0x36b452eb GSEventRunModal + 75

8 UIKit 0x34e99301 UIApplicationMain + 1121

9 AutoScene 0x000031b7 main(main.m:7)

我的计时器是:

[NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(resetAdTimer) userInfo:nil repeats:YES];

我不知道这是不是同样的问题,但我经历过从背景返回应用程序的时间,它只是挂起..它似乎也挂了30秒,这让我相信它是定时器代码。

这是管理广告获取的一种糟糕方式吗? 计时器代码长时间进入后台时是否会搞砸?

谢谢你的帮助!

您应该在appWillResignActive中使计时器无效,并在appWillBecome中再次创建它。 来自文档......

- (void)applicationWillResignActive:(UIApplication *)application 

您应该使用此方法暂停正在进行的任务,禁用计时器,并降低OpenGL ES帧速率。 游戏应该使用这种方法暂停游戏。 处于非活动状态的应用程序在等待转换为活动状态或后台状态时应执行最少的工作。

Swift 4.2这样做

override func viewDidLoad() {
        let notificationCenter = NotificationCenter.default
        notificationCenter.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
        notificationCenter.addObserver(self, selector: #selector(appBecomesActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}


@objc func appWillResignActive() {
    //to background
}

@objc func appBecomesActive() {
    //to front
}

不要忘记删除观察者。

    notificationCenter.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
    notificationCenter.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)

灵感来自这里https://www.hackingwithswift.com/example-code/system/how-to-detect-when-your-app-moves-to-the-background

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM