TTimer not working while iOS app in background

2019-09-12 10:44发布

问题:

I have an app that needs to perform some actions based on a TTimer.

When the app becomes inactive (in background), the timer stops working.

I could not find any relevant options for UIBackgroundModes.

How can I make a timer keeps running?

回答1:

iOS pauses your app automatically shortly after it goes into the background. You need to let iOS know that you are going to continue operating in the background.

In Project > Options > Version Info you can add to the array key UIBackgroundModes the string values for the services that require to continue running in the background. This gets added to the info.plist for your project on iOS.

You can consult Apple's documentation on what these values do . . .

  • Value - Description
  • audio - The app plays audible content in the background.
  • location - The app provides location-based information to the user and requires the use of the standard location services (as opposed to the significant change location service) to implement this feature.
  • voip - The app provides Voice-over-IP services. Apps with this key are automatically launched after system boot so that the app can reestablish VoIP services. Apps with this key are also allowed to play background audio.
  • fetch - The app requires new content from the network on a regular basis. When it is convenient to do so, the system launches or resumes the app in the background and gives it a small amount of time to download any new content. This value is supported in iOS 7.0 and later.
  • remote-notification - The app uses remote notifications as a signal that there is new content available for download. When a remote notification arrives, the system launches or resumes the app in the background and gives it a small amount of time to download the new content. This value is supported in iOS 7.0 and later.
  • newsstand-content - The app processes content that was recently downloaded in the background using the Newsstand Kit framework, so that the content is ready when the user wants it. This value is supported in iOS 5.0 and later.
  • external-accessory - The app communicates with an accessory that delivers data at regular intervals. This value is supported in iOS 5.0 and later.
  • bluetooth-central - The app uses the CoreBluetooth framework to communicate with a Bluetooth accessory while in the background. This value is supported in iOS 5.0 and later.
  • bluetooth-peripheral - The app uses the CoreBluetooth framework to communicate in peripheral mode with a Bluetooth accessory. The system will alert the user to the potential privacy implications of apps with this key set. See Best Practices for Maintaining User Privacy for more information on privacy. This value is supported in iOS 6.0 and later.

Notice you need to actually select the mode that matches what you are doing. You can't just select fetch when really all you are doing is background processing.