[html]
/////////第一次打開時判斷網絡狀態
- (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;
}
}
}