1

我已经尝试了这个网站上的一些帖子。但是在我的 iphone 应用程序中,如果没有连接互联网,它不会显示任何错误。它只是显示加载视图。我为此使用了以下代码

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
error=nil;
if(error != nil)
{

    UIAlertView * alert;
    if([[error localizedDescription] isEqualToString:@"no Internet connection"])
    {
        alert = [[UIAlertView alloc] initWithTitle:@"No Internet connection" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }

    else
    {
        alert = [[UIAlertView alloc] initWithTitle:@"Connection failed" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
    [alert release];
} 
}

即使未连接互联网,也不会显示此警告。谁能帮我?提前致谢

4

3 回答 3

4

请参阅Apple 提供的有关 Reachability示例代码。

并实施某些必要的方法。

于 2012-06-26T07:03:58.420 回答
0

是 NSUrlConnection 当前支持的错误代码

没有互联网连接的错误代码是 NSURLErrorNotConnectedToInternet = -1009,

当您遇到 NSError* 错误时,您可以在您的情况下使用它

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if(error != nil)
    {
        if ([error code] == NSURLErrorNotConnectedToInternet) {
          //not connected to internet
       }
    }

}
于 2012-06-26T05:43:07.613 回答
0

使用此代码...

定义这个

#define AF_INET     2

并实现这一点,

- (BOOL) connectedToNetwork

{

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)
{    
    printf("Error. Could not recover network reachability flags\n");
    return 0;
}   
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
return (isReachable && !needsConnection) ? YES : NO;

}

使用 bool 进行检查,

    BOOL check = [self connectedToNetwork];

然后检查这个条件,

    if (!check) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning!" message:@"Your internet connection is currently unavailable. Please try to connect later."
                                                   delegate:self cancelButtonTitle:@"Done" otherButtonTitles:nil];
    [alert show];
    [alert release];
}
于 2012-06-26T07:26:27.483 回答