/第一次打开时判断网络状态 - (int) connectedToNetwork { NSString *kindStr; int kind; //创建零地址,0.0.0.0的地址表示查询本机的网络连接状态 struct sockaddr_in zeroAddress; bzero(&zeroAddress, sizeof(zeroAddress)); zeroAddress.sin_len = sizeof(zeroAddress); zeroAddress.sin_family = AF_INET; // Recover reachability flags SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress); SCNetworkReachabilityFlags flags; //获得连接的标志 BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags); CFRelease(defaultRouteReachability); //如果不能获取连接标志,则不能连接网络,直接返回 if (!didRetrieveFlags) { kindStr = @"获取信息失败"; kind = -1; } else{ //根据获得的连接标志进行判断 BOOL isReachable = flags & kSCNetworkFlagsReachable; BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired; if((isReachable && !needsConnection)==YES) { ///能够连接网络 if((flags& kSCNetworkReachabilityFlagsIsWWAN)==kSCNetworkReachabilityFlagsIsWWAN) { kindStr = @"手机网络"; kind = 0; } else { kindStr =@"wifi连接网络"; kind = 1; } } else{ kindStr =@"不能连接网络"; kind = -1; } } return kind; } 设置网络监听 -(void)SetJianCeNetwork { //开启网络状况的监听 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil]; hostReach = [[Reachability reachabilityWithHostname:@"www.xtox.net"] retain];//可以以多种形式初始化 [hostReach startNotifier]; //开始监听,会启动一个run loop } // 连接改变 - (void) reachabilityChanged: (NSNotification* )note { Reachability* curReach = [note object]; NSParameterAssert([curReach isKindOfClass: [Reachability class]]); [self updateInterfaceWithReachability: curReach]; } //处理网络连接改变后的情况 - (void) updateInterfaceWithReachability: (Reachability*) curReach { //对连接改变做出响应的处理动作。 NetworkStatus status = [curReach currentReachabilityStatus]; if (status == NotReachable) { //没有连接到网络就弹出提实况 isNetType = -1; UIAlertView *alert =[[UIAlertView alloc]initWithTitle:nil message:@"网络连接失败,请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil]; [alert show]; [alert release]; } else if(status == ReachableViaWiFi ||status == ReachableViaWWAN) { if(status == ReachableViaWWAN) { isNetType = 0; } else if(status == ReachableViaWiFi) { isNetType = 1; } // NSThread *initThread = [[NSThread alloc]initWithTarget:self selector:@selector(InitThreadFunc:) object:self]; [initThread start]; return; } } -(void)InitThreadFunc:(id)sender { //isNetType = [self connectedToNetwork]; if(isNetType!=-1) { if([g_json Test]==YES) { [g_json UserLogin:0 pass:nil]; [self GetUpdate]; return; } else { isNetType = -1; } } }