我使用可访问性类来检查代码中的wifi连接。但有时会出现问题,即wifi已打开,但没有或低互联网连接,这里我的代码在循环中运行,等待来自被调用的webservice的任何响应,并且有时会出现挂起和崩溃。 当我在AlertView上点击OK时会执行以下代码,这会从webservice中提取一些数据 这是我的代码:
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];
}
我是Objective C的新手。 Plz帮助我,提前谢谢。抱歉我的语法错误。
答案 0 :(得分: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];
}
答案 1 :(得分: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 is Reachable意味着可以访问Wifi并且存在Internet连接。
感谢所有人提供您对我们问题的快速回答。 对不起我的语法错误。