2011-07-15 187 views
2

我使用可達性類來檢查我的代碼中的WiFi連接。但有時問題出現,無線網絡打開,但沒有或低互聯網連接,在這裏我的代碼循環運行,等待任何來自所謂的web服務的響應,並掛斷和崩潰有時。要檢查wifi是否打開,但沒有互聯網連接

 Reachability *ReachObj = [Reachability reachabilityForInternetConnection]; 
    [ReachObj startNotifier]; 
    NetworkStatus remoteHostStatus = [ReachObj currentReachabilityStatus]; 

    if (remoteHostStatus==ReachableViaWiFi) 
    { 
     SecondView *ObjSecView=[[SecondView alloc]init]; 
     [self presentModalViewController:ObjSecView animated:YES]; 
    } 

    else 
     if (remoteHostStatus==NotReachable) 
    { 
     FirstView *objFrstView=[[FeedBackPopOverViewController alloc]init]; 
     [self presentModalViewController:objFrstView animated:YES];  
    } 

傢伙,我新來目的C. PLZ幫助我,在此先感謝: 下面的代碼,當我在從web服務 翻出一些數據這裏是我的代碼AlertView點擊OK執行。對於我的語法錯誤感到抱歉。

回答

0

試試這個..

SCNetworkReachabilityFlags flags; 

SCNetworkReachabilityRef reachability=SCNetworkReachabilityCreateWithName(NULL, [@"your  web sevice url" UTF8String]); 

SCNetworkReachabilityGetFlags(reachability, &flags); 
BOOL reachable=!(flags & kSCNetworkReachabilityFlagsConnectionRequired); 

CFRelease(reachability); 
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]; 


if([NSURLConnection canHandleRequest:request] && reachable) 
{ 
conn=[NSURLConnection connectionWithRequest:request delegate:self]; 

if(conn) 
{ 
    ////   

} 
else 
{ 
    [_delegate performSelector:@selector(httpDataDidFailLoadingWithReason:) 
        withObject:@"No Internet Connection" afterDelay:0.1]; 
} 

} 


-(void) httpDataDidFailLoadingWithReason:(NSString*)reason 
{ 

UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"abc" 
                message:reason 
                delegate:self cancelButtonTitle:@"OK" 
              otherButtonTitles:nil]; 
[alertView show]; 
[alertView release]; 

    } 
0
-(void)loginButtonTouched 
{ 
    bool success = false; 
    const char *host_name = [@"www.google.com" 
       cStringUsingEncoding:NSASCIIStringEncoding]; 

    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName 
                (NULL, host_name); 
    SCNetworkReachabilityFlags flags; 
    success = SCNetworkReachabilityGetFlags(reachability, &flags); 
    bool isAvailable = success && (flags & kSCNetworkFlagsReachable) && 
         !(flags & kSCNetworkFlagsConnectionRequired); 

    if (isAvailable) 
    { 
     NSLog(@"Host is reachable: %d", flags); 
     // Perform Action if Wifi is reachable and Internet Connectivity is present 
    } 
    else 
    { 
     NSLog(@"Host is unreachable"); 
     // Perform Action if Wifi is reachable and Internet Connectivity is not present 
    }  
} 

當loginButtonTouched方法被調用,我們檢查 「www.google.com」 可達與否。 SCNetworkReachabilityFlags返回幫助我們瞭解互聯網連接狀態的標誌。 如果isAvailable變量返回「true」,那麼Host是可達的意味着Wifi可用並且Internet連接存在。

並感謝所有提供您對我們問題的快速回答。 對不起,我的語法錯誤。