Tips for IOS programming when network status changes

Source: Internet
Author: User

We all know that a large number of apps are currently using the network, but how can we give users a prompt when the network is disconnected or the network status changes, this is a question worth pondering. Some people say that setting up monitoring and scanning at intervals is acceptable, but it is a waste of resources for mobile phones. So we only need to determine whether the network status of the mobile phone has changed. When the network status changes, we can start the relevant program. Is this good? So let's share a piece of code for everyone, I hope everyone can make progress together.

You also need to import the Third-Party Library:

#import
 

The Code is as follows:

HHLAppDelegate. h

#import 
 
  #import
  
   #import "Reachability.h"@interface HHLAppDelegate : UIResponder 
   
    @property (strong, nonatomic) UIWindow *window;@property (retain,nonatomic) Reachability *hostReach;@end
   
  
 


HHLAppDelegate. m

# Import "HHLAppDelegate. h "# import" Reachability. h "@ implementation HHLAppDelegate-(void) dealloc {[_ window release]; [_ hostReach release]; [super dealloc];}-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions {self. window = [[[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds] autorelease]; // Override point for customization after application launch. self. window. backgroundColor = [UIColor whiteColor]; [[nsicationcenter center defacenter center] addObserver: self selector: @ selector (reachabilityChanged :) name: kReachabilityChangedNotification object: nil]; self. hostReach = [[Reachability reachabilityWithHostName: @ "www.baidu.com"] retain]; [self. hostReach startNotifier]; [self. window makeKeyAndVisible]; return YES;}-(void) reachabilityChanged :( NSNotification *) note {Reachability * preachability = [note object]; NSParameterAssert ([preachability isKindOfClass: [Reachability class]); NSString * pStr_3G = @ "current network is 2G or 3G"; NSString * pStr_WiFi = @ "current network is Wi-Fi "; // NSString * pStr_WLAN = @ "the current network is WLAN"; NSString * pStr_NO = @ "the current network is disconnected"; switch ([preachability currentReachabilityStatus]) {case NotReachable: [self alertShow: pStr_NO]; break; case ReachableViaWiFi: [self alertShow: pStr_WiFi]; break; case when: [self alertShow: pStr_3G]; break; // case ReachableViaWWAN: // [self alertShow: pStr_WLAN]; // default: break;}-(void) alertShow :( NSString *) mes {UIAlertView * AlertView = [[UIAlertView alloc] initWithTitle: @ "notification" message: mes delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil]; [AlertView show]; [AlertView release];}-(void) applicationWillResignActive :( UIApplication *) application {// Sent when the application is about to move from active to inactive state. this can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. games shocould use this method to pause the game .} -(void) applicationDidEnterBackground :( UIApplication *) application {// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits .} -(void) applicationWillEnterForeground :( UIApplication *) application {// Called as part of the transition from the background to the inactive state; here you can undo records of the changes made on entering the background .} -(void) applicationDidBecomeActive :( UIApplication *) application {// Restart any tasks that were paused (or not yet started) while the application was inactive. if the application was previusly in the background, optionally refresh the user interface .} -(void) applicationWillTerminate :( UIApplication *) application {// Called when the application is about to terminate. save data if appropriate. see also applicationDidEnterBackground :.} @ end


Reachability. h


#import 
 
  #import 
  
   typedef enum {NotReachable = 0,ReachableViaWiFi,ReachableViaWWAN} NetworkStatus;#define kReachabilityChangedNotification @"kNetworkReachabilityChangedNotification"@interface Reachability: NSObject{BOOL localWiFiRef;SCNetworkReachabilityRef reachabilityRef;}//reachabilityWithHostName- Use to check the reachability of a particular host name. + (Reachability*) reachabilityWithHostName: (NSString*) hostName;//reachabilityWithAddress- Use to check the reachability of a particular IP address. + (Reachability*) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress;//reachabilityForInternetConnection- checks whether the default route is available.  //  Should be used by applications that do not connect to a particular host+ (Reachability*) reachabilityForInternetConnection;//reachabilityForLocalWiFi- checks whether a local wifi connection is available.+ (Reachability*) reachabilityForLocalWiFi;//Start listening for reachability notifications on the current run loop- (BOOL) startNotifier;- (void) stopNotifier;- (NetworkStatus) currentReachabilityStatus;//WWAN may be available, but not active until a connection has been established.//WiFi may require a connection for VPN on Demand.- (BOOL) connectionRequired;@end
  
 


Reachability. m


#import 
 
  #import 
  
   #import 
   
    #import #import 
    
     #import 
     
      #import 
      
       #import "Reachability.h"#define kShouldPrintReachabilityFlags 1static void PrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment){#if kShouldPrintReachabilityFlags NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n",(flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-',(flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-',(flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-',(flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-',(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-',(flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-',(flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-',(flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-',(flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-',comment);#endif}@implementation Reachabilitystatic void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info){#pragma unused (target, flags)NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback");NSCAssert([(NSObject*) info isKindOfClass: [Reachability class]], @"info was wrong class in ReachabilityCallback");//We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively// in case someon uses the Reachablity object in a different thread.NSAutoreleasePool* myPool = [[NSAutoreleasePool alloc] init];Reachability* noteObject = (Reachability*) info;// Post a notification to notify the client that the network reachability changed.[[NSNotificationCenter defaultCenter] postNotificationName: kReachabilityChangedNotification object: noteObject];[myPool release];}- (BOOL) startNotifier{BOOL retVal = NO;SCNetworkReachabilityContextcontext = {0, self, NULL, NULL, NULL};if(SCNetworkReachabilitySetCallback(reachabilityRef, ReachabilityCallback, &context)){if(SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)){retVal = YES;}}return retVal;}- (void) stopNotifier{if(reachabilityRef!= NULL){SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);}}- (void) dealloc{[self stopNotifier];if(reachabilityRef!= NULL){CFRelease(reachabilityRef);}[super dealloc];}+ (Reachability*) reachabilityWithHostName: (NSString*) hostName;{Reachability* retVal = NULL;SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]);if(reachability!= NULL){retVal= [[[self alloc] init] autorelease];if(retVal!= NULL){retVal->reachabilityRef = reachability;retVal->localWiFiRef = NO;}}return retVal;}+ (Reachability*) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress;{SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress);Reachability* retVal = NULL;if(reachability!= NULL){retVal= [[[self alloc] init] autorelease];if(retVal!= NULL){retVal->reachabilityRef = reachability;retVal->localWiFiRef = NO;}}return retVal;}+ (Reachability*) reachabilityForInternetConnection;{struct sockaddr_in zeroAddress;bzero(&zeroAddress, sizeof(zeroAddress));zeroAddress.sin_len = sizeof(zeroAddress);zeroAddress.sin_family = AF_INET;return [self reachabilityWithAddress: &zeroAddress];}+ (Reachability*) reachabilityForLocalWiFi;{struct sockaddr_in localWifiAddress;bzero(&localWifiAddress, sizeof(localWifiAddress));localWifiAddress.sin_len = sizeof(localWifiAddress);localWifiAddress.sin_family = AF_INET;// IN_LINKLOCALNETNUM is defined in 
       
         as 169.254.0.0localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM);Reachability* retVal = [self reachabilityWithAddress: &localWifiAddress];if(retVal!= NULL){retVal->localWiFiRef = YES;}return retVal;}#pragma mark Network Flag Handling- (NetworkStatus) localWiFiStatusForFlags: (SCNetworkReachabilityFlags) flags{PrintReachabilityFlags(flags, "localWiFiStatusForFlags");BOOL retVal = NotReachable;if((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect)){retVal = ReachableViaWiFi;}return retVal;}- (NetworkStatus) networkStatusForFlags: (SCNetworkReachabilityFlags) flags{PrintReachabilityFlags(flags, "networkStatusForFlags");if ((flags & kSCNetworkReachabilityFlagsReachable) == 0){// if target host is not reachablereturn NotReachable;}BOOL retVal = NotReachable;if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0){// if target host is reachable and no connection is required// then we'll assume (for now) that your on Wi-FiretVal = ReachableViaWiFi;}if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)){// ... and the connection is on-demand (or on-traffic) if the// calling application is using the CFSocketStream or higher APIsif ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0){// ... and no [user] intervention is neededretVal = ReachableViaWiFi;}}if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN){// ... but WWAN connections are OK if the calling application// is using the CFNetwork (CFSocketStream?) APIs.retVal = ReachableViaWWAN;}return retVal;}- (BOOL) connectionRequired;{NSAssert(reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef");SCNetworkReachabilityFlags flags;if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)){return (flags & kSCNetworkReachabilityFlagsConnectionRequired);}return NO;}- (NetworkStatus) currentReachabilityStatus{NSAssert(reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef");NetworkStatus retVal = NotReachable;SCNetworkReachabilityFlags flags;if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)){if(localWiFiRef){retVal = [self localWiFiStatusForFlags: flags];}else{retVal = [self networkStatusForFlags: flags];}}return retVal;}@end
       
      
     
    
   
  
 

The specific image is as follows:


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.