Sachin
Sachin

Reputation: 343

IOS Reachability notification in Background

I want to do some tasks as soon as user comes online even he is in background. I am using Reachability class for checking internet. But this class is not notifying me when i am at background. I know people asked this question earlier but didn't got any solutions there. If i use beginBackgroundTaskWithExpirationHandler. It gives me 3 to 4 min only, after that if network change i am not getting any notification. Please suggest me something.I think it is possible because native mail app work in that manner and my app support iOS7 only.

Upvotes: 4

Views: 2950

Answers (3)

Lal Krishna
Lal Krishna

Reputation: 16160

use Background Fetch mode from Capabilities. Firstable you need to check the checkbox for background mode:

Project settings -> Capabilities -> BackgroundMode -> Background Fetch

Then you need to ask for time interval as often as you can the sooner the better so i suggest application:didFinishLaunchingWithOptions: and you need to put this line:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
    return YES;
}

UIApplicationBackgroundFetchIntervalMinimum - The smallest fetch interval supported by the system.

And then when background fetch will fire you can check in AppDelegate with method:

-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    [reachability startNotifier];
    NetworkStatus status = [reachability currentReachabilityStatus];

    switch (status) {
        case NotReachable: {
            NSLog(@"no internet connection");
            break;
        }
        case ReachableViaWiFi: {
            NSLog(@"WiFi");
            break;
        }
        case ReachableViaWWAN: {
            NSLog(@"cellular");
            break;
        }
    }
    completionHandler(YES);
}

Supports iOS 7.0+

Upvotes: 0

Basheer_CAD
Basheer_CAD

Reputation: 4919

You cannot get notification form your classes while the app is in the background, you can make use of the new iOS 7 background fetching possibilities. Here is a tutorial http://www.objc.io/issue-5/multitasking.html

Upvotes: 2

Wain
Wain

Reputation: 119031

It is not possible to do exactly what you want. You can not base your assumptions on Apple supplied apps as Apple has access to processes / APIs that you don't. Mail is running as a daemon process on the device and your app will never be doing that.

Read about the iOS 7 background capabilities. It is based around your app getting processing time just before the user wants to run the app - not at arbitrary times of your choice.

Upvotes: 3

Related Questions