stkvtflw
stkvtflw

Reputation: 13507

Objective-c: undeclared identifier applicationDidEnterBackground

I'm trying to use code from this example:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{
        // Clean up any unfinished task business by marking where you
        // stopped or ending the task outright.
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do the work associated with the task, preferably in chunks.

        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}

I'm a react-native developer, so sorry, probably this is a silly question :)

How do i know where from should i import this method? applicationDidEnterBackground

Docs aren't give me answer for this either.

Upvotes: 0

Views: 840

Answers (1)

Mert Buran
Mert Buran

Reputation: 3017

There are 2 ways of doing this:

AppDelegate

You should implement this method in your AppDelegate.m You can find your app's delegate by looking at main.m file and you will something like

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

AppDelegate is your app's delegate class.

NSNotificationCenter

There is a built-in UIApplicationDidEnterBackgroundNotification notification which is declared in UIApplication.h and you can add any kind of object as observer to NSNotificationCenter.

[[NSNotificationCenter defaultCenter]
     addObserver:{myObserver}
     selector:@selector({myObserverMethod}:) // adding ":" at the end will provide you the sent notification as parameter to your method
     name:UIApplicationDidEnterBackgroundNotification
     object:nil];

Now you need to implement {myObserverMethod}:(NSNotification *)notification in your {myObserver} class

// MyObserver.m
- (void)myObserverMethod:(NSNotification *)notification {
    UIApplication *application = notification.object;
    // Now you can call `[application beginBackgroundTask:]` or etc.
    NSLog(@"applicationDidEnterBackground");
}

NOTE: Don't forget that prior to iOS 9 you need to call [[NSNotificationCenter defaultCenter] removeObserver:{myObserver}] when you are done with it!

Upvotes: 1

Related Questions