您的位置:首页 > 理论基础 > 计算机网络

IOS网络连接的学习

2012-10-22 10:44 113 查看
struct sockaddr_in zeroAddress;

bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;

SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;

BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);

if (!didRetrieveFlags) {
printf("Error. Count not recover network reachability flags\n");
}

BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;

NSString *result;
if ((isReachable && !needsConnection) ? YES : NO) {
result = @"Connection Successed!!!";
}else {
result = @"Connection Faild!!!";
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"TestConnection"
message:result delegate:self
cancelButtonTitle:@"OK,I Know"
otherButtonTitles:nil];
[alert show];
///////////////测试网络连接/////////////////

NSString *connectionKind;
// 测试连接可用性
Reachability *hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
// 判断连接类型
switch ([hostReach currentReachabilityStatus]) {
case NotReachable:
connectionKind = @"没有网络链接";
break;
case ReachableViaWiFi:
connectionKind = @"当前使用的网络类型是WIFI";
break;
case ReachableViaWWAN:
connectionKind = @"当前使用的网络链接类型是WWAN(3G)";
break;
default:
break;
}

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络链接类型"
message:connectionKind
delegate:self
cancelButtonTitle:@"知道了,谢谢"
otherButtonTitles:nil];
[alert show];
///////////////测试连接类型/////////////////

[self.textField resignFirstResponder];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *message;
Reachability *hostReach = [Reachability reachabilityWithHostName:self.textField.text];
if ([hostReach currentReachabilityStatus] == NotReachable) {
message = @"连接失败";
}else {
message = @"连接成功";
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"结果"
message:message
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息