IOS Reachability notification in Background

眉间皱痕 提交于 2019-12-20 01:36:53

问题


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.


回答1:


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




回答2:


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.




回答3:


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+



来源:https://stackoverflow.com/questions/22197630/ios-reachability-notification-in-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!