我已经尝试过本网站提供的一些帖子。但在我的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];
}
}
即使未连接互联网,也不会显示此警告。谁能帮我?提前致谢
答案 0 :(得分:4)
请参阅Apple的this示例代码,了解可达性。
并实施某些必要的方法。
答案 1 :(得分:0)
here 是NSUrlConnection目前支持的错误代码
没有互联网连接的错误代码是NSURLErrorNotConnectedToInternet = -1009,
当你遇到NSError *错误
时,你可以在你的情况下使用它- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
if(error != nil)
{
if ([error code] == NSURLErrorNotConnectedToInternet) {
//not connected to internet
}
}
}
答案 2 :(得分: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];
}