App background to foreground

with this code my app works good,but when i get back in foreground all function are disable....who can I get work in foreground?



func applicationDidEnterBackground(_ application: UIApplication) {
var finished = false
var bgTask: UIBackgroundTaskIdentifier = 0;
bgTask = application.beginBackgroundTask(withName:"MyBackgroundTask", expirationHandler: {() -> Void in
// Time is up.
if bgTask != UIBackgroundTaskInvalid {
// Do something to stop our background task or the app will be killed
finished = true
}
})
// Perform your background task here
print("The task has started")
while !finished {
print("Not finished")
// when done, set finished to true
// If that doesn't happen in time, the expiration handler will do it for us
}
// Indicate that it is complete
application.endBackgroundTask(bgTask)
bgTask = UIBackgroundTaskInvalid
}

Replies

The approach you’re using here won’t work. You are expected to return from

applicationDidEnterBackground(_:)
promptly. Doing your background work synchronously within
applicationDidEnterBackground(_:)
is going to cause problems. For example, your background task expiry handle is called on the main thread, but the main thread is stuck within
applicationDidEnterBackground(_:)
, so it won’t be able to call the expiry handler.

The standard approach for doing this is to start a background task in

applicationDidEnterBackground(_:)
and then run the actual background work asynchronously (if it’s I/O bound) or on a secondary thread/queue (if it’s CPU bound). The presence of the background task will prevent your app from suspended after it returns from
applicationDidEnterBackground(_:)
, thus allowing the actual work to complete.

Finally, I recommend you read my UIApplication Background Task Notes, which has a bunch of background (hey hey!) on this subject.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"