NSTimer events do no occur when screen locked on i

2019-06-12 12:01发布

I've seen this come up a few times but I haven't really seen a definite answer...

Since iOS 5 my application seems to run into the problem that if the user locks the screen my NSTimer stops firing after about 20 seconds in the lock screen. This makes my app which plays a sound every time the timer fires pointless if the user locks the screen.

This has only happened since I updated my device to iOS 5.

My question is that 1. Is there any workaround to having this same functionality work on updated devices or 2. What is the recommended approach to not receiving bad reviews if your app doesn't run while locked.

2条回答
倾城 Initia
2楼-- · 2019-06-12 12:35

In iOS5, Apple has introduced more background task modes, including "audio", "location", "voip", "newsstand-content", "external-accessory" and "bluetooth-central". I think you can determine which mode you can use in your app. The link is http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW24

查看更多
我命由我不由天
3楼-- · 2019-06-12 12:55

When the user locks the screen, the app enters the 'inactive' state. This is similar to but not identical toputting your app into the background. Apple's documentation states "The app is running in the foreground but is currently not receiving events. (It may be executing other code though.)"

However, after entering the inactive state the iPhone does go completely to sleep, unless something is running to keep it active... waiting for an NSTimer to fire does not satisfy this criteria, apparently. There is discussion in this previous question. One solution, it would appear, is to play your sound when your timer fires, and in the interim, play a silent sound continuously in order to prevent the iPhone from sleeping. A hack, but at least in this case not a completely ugly hack since using a sound in order to keep the iPhone awake in order to play a sound has a kind of symmetry.

Previously linked content:
From Apple's guidelines regarding implementing long-running background tasks:

Playing Background Audio
An app that plays audio continuously (even while the app is running in the background) can register as a background audio app by including the UIBackgroundModes key (with the value audio) in its Info.plist file. Apps that include this key must play audible content to the user while in the background.

Are you implementing this in your app? If not, that's your issue.

Regarding #2: You could update the description of the app to indicate it does not work with the screen locked, but better would be just to make it so that it works as the user would expect. :)

查看更多
登录 后发表回答