user3196945
user3196945

Reputation: 19

In iOS, is there a way to execute a piece of code after certain amount of time after I quit the application?

Is there a way to execute a piece of code after certain amount of time after I quit the application?

I mean press the home button

Upvotes: 0

Views: 175

Answers (3)

donuttakedonuts
donuttakedonuts

Reputation: 11

https://developer.apple.com/library/ios/documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIApplicationDelegate/applicationDidEnterBackground:

The applicationDidEnterBackground method is called on the appDelegate in iOS 4.0 and onwards, upon the home button being pressed and the user's view exiting to the home screen. You can then use a [NSTimer]

(https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/classes/NSTimer_Class/Reference/NSTimer.html)

to execute whatever code you want at some point later. Note, though, that iOS likes applicationDidEnterBackground to return within about 5 seconds; your application can start a background task with the method beginBackgroundTaskWithExpirationHandler.

Upvotes: 1

Harunmughal
Harunmughal

Reputation: 367

if You want to execute some code after some time than you can use the NSTimer.Thanks

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

Upvotes: 1

nalyd88
nalyd88

Reputation: 5128

From the Apple docs:

Your app delegate’s applicationDidEnterBackground: method has approximately 5 seconds to finish any tasks and return. In practice, this method should return as quickly as possible. If the method does not return before time runs out, your app is killed and purged from memory. If you still need more time to perform tasks, call the beginBackgroundTaskWithExpirationHandler: method to request background execution time and then start any long-running tasks in a secondary thread. Regardless of whether you start any background tasks, the applicationDidEnterBackground: method must still exit within 5 seconds.

Read the whole article for more information but basically when someone presses the home button the applicationDidEnterBackground: method will get called. In that method setup your code on a separate thread using beginBackgroundTaskWithExpirationHandler:.

Hope that helps!

Upvotes: 1

Related Questions