我尝试使用此代码在我的应用中检查网络连接,但它始终使用连接失败的代码。这是我的代码:
- (void)applicationDidBecomeActive:(UIApplication *)application {
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: @"example.com/in-app/net.test" ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
if([serverOutput isEqualToString:@"internet is working"]){
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Conection Succesful" message:@"You have succesfully connected to our server. "
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertsuccess show];
[alertsuccess release];
} else {
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Connection Unsuccesful" message:@"failed to connect"
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertsuccess show];
[alertsuccess release];
}
}
再次,如何检查Objective-C中是否可以访问服务器?此代码应该工作,服务器端代码可以正常工作,但在应用程序中却没有。
答案 0 :(得分:3)
URLWithString
期望符合RFC 2396的URL包含该方案(例如“http”):
[NSURL URLWithString:@"http://example.com/in-app/net.test"]
答案 1 :(得分:1)
更简单的实现方法是使用Apple的Reachability类,它使用SystemConfiguration框架检查是否有可用的Internet连接。
我强烈建议您查看苹果开发者网站的这两个链接。