我在目标C中遇到了一个奇怪的问题。
我有这个代码片段。问题是,当我在Iphone或ipad上启动应用程序4-5次时,我得到的远程服务器找不到,并且在终止应用程序4-5次后一切正常。服务器可用,并且能够从移动Safari浏览。
任何帮助都将不胜感激。
NSURL *scriptUrl = [NSURL URLWithString:@"https://www.zzzzzz-zz.zzzzzz-zzzz.com/zzzzz/"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
if (data)
{
//COMPAS is reachable
NSLog(@"Device is connected to the internet");
}
else
{
//COMPAS is not reachable
NSLog(@"Device is connected to the internet");
[self performSelectorOnMainThread:@selector(showHostAlert:) withObject:nil waitUntilDone:NO];
}发布于 2015-04-17 18:22:26
我的建议是使用NSURLConnection或NSURLSession获取数据。使用contentsOfURL的NSData、NSString等类的工厂方法不能很好地工作,除了本地URLS。如果从远程URL获取数据时出现错误,则无法获取错误状态。
因此,继续使用connection或session类发出请求,然后在完成时使用它们提供的数据。如果您没有获得数据,那么检查这些类将提供的NSError对象。
发布于 2015-04-17 19:08:09
NSData上的dataWithContentsOfUrl方法仅适用于从本地资源加载数据。
同步获取数据示例:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverAddress]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
[request setHTTPMethod: @"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError]; https://stackoverflow.com/questions/29696416
复制相似问题