简体   繁体   中英

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.

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.

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

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 +

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM