2013-05-05 60 views
-3

我试图检查我的应用程序中使用此代码的网络连接,但它始终使用连接不成功的代码。这是我的代码:如何检查服务器是否可以在Objective-C中访问?

- (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中访问?此代码应该工作和服务器端代码工作,但在应用程序它不。

+1

你有没有尝试登录'serverOutput'? – Dave 2013-05-05 17:15:17

+0

多数民众赞成什么即时通讯做这第二次,生病后的结果 – 2013-05-05 17:16:06

回答

3

URLWithString需要一个RFC 2396符合网址,其中包括计划(如“HTTP”):

[NSURL URLWithString:@"http://example.com/in-app/net.test"] 
1

一个实现这一目标的更简单的方法是使用苹果可达类,它使用SystemConfiguration框架检查有一个互联网连接可用。

我强烈建议你看看这两个链接到苹果的开发者网站。

+2

是的,应该只指出,SCNetworkReachability测试目标主机的可达性,但不是主机实际上运行并接收数据包。 – 2013-05-06 07:37:14

相关问题