programmatically prevent app from running in background iOS

4 Solutions Collect From Internet About “programmatically prevent app from running in background iOS”

You can’t use exit(0) b/c apple does not allow you to close the app without user knowing it.

From Technical Q&A QA1561 How do I programmatically quit my iPhone application?.

There is no API provided for gracefully terminating an iPhone
application. Under the iPhone OS, the
user presses the Home button to close
applications. Should your application
have conditions in which it cannot
provide its intended function, the
recommended approach is to display an
alert for the user that indicates the
nature of the problem and possible
actions the user could take – turning
on WiFi, enabling Location Services,
etc. Allow the user to terminate the
application at their own discretion.

Add the variable UIApplicationExitsOnSuspend (Application does not run in background) to your applications plist and assign the value YES.

You can close the app by calling exit(0) in applicationDidEnterBackground.

Calling exit() is discouraged, and not informing the user that the app is going to terminate is also discouraged. So you need to get the OS to kill your app (as it normally would do over a long enough period of operation) while simultaneously informing the user. One way of doing this, while using only legal APIs, is to dirty absolutely as many memory pages as possible (malloc and bzero), then call Safari with a URL to a hoggish website explaining why the app is going to quit. Safari will require enough memory to display the website that your app will be terminated by the OS, just as the user is being properly informed.

Sleeping until the OS kill timer kills your app will also kill your app, but this non-responsive delay will lock up the UI, which isn’t a good user experience.