2011-05-15 116 views
7

我有一个for循环,当前循环4次。Objective-C - 检查URL是否存在

//Add all the URLs from the server to the array 
    for (int i = 1; i <= 5; i++){ 
     NSString *tempString = [[NSString alloc] initWithFormat : @"http://photostiubhart.comoj.com/GalleryImages/%dstiubhart1.jpg", i]; 
     [myURLS addObject: [NSURL URLWithString:tempString]]; 
     [tempString release]; 
    } 

正如你可以看到网址中有一个数字,得到由1每次循环递增,以创建一个新的URL下一个图像会。但是,服务器上的图像数量不一定是4,可能会更多,甚至更少。我的问题是,有没有一种方法可以检查URL中是否存储了图像?如果没有,请打破循环并继续执行程序?

感谢,

杰克

+0

可能[如何检查一个文件是否存在于特定的URL?](http://stackoverflow.com/questions/2021391/how-to-check-if-a-file-exists-at-particular-url) – zoul 2011-05-15 15:43:10

回答

16

这里是思想的检查与HTTP响应

NSURLRequest *request; 
NSURLResponse *response = nil; 
NSError **error=nil; 
NSData *data=[[NSData alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error]]; 
NSString* retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
// you can use retVal , ignore if you don't need. 
NSInteger httpStatus = [((NSHTTPURLResponse *)response) statusCode]; 
NSLog(@"responsecode:%d", httpStatus); 
// there will be various HTTP response code (status) 
// you might concern with 404 
if(httpStatus == 404) 
{ 
    // do your job 
} 

while(httpStatus == 200){ 
    static int increment = 0; 
    increment++; 
    // check other URL yoururl/somthing/increment++ 
} 

但是这将是缓慢的。我的建议是,如果您使用自己的网络服务器,那么您可以先发送所有图像信息。我敢肯定,你在annonymous或其他网站做这个工作:) 让我知道,如果它可以帮助你或不

-2

这里是检查是否网址有效最简单的方法:

NSURL *URL = [NSURL URLWithString:@"www.your.unvalidated.yet/url"]; 

if ([[UIApplication sharedApplication] canOpenURL:[URL absoluteURL]]) 
{ 
    //your link is ok 
} 
+0

这个不会检查网址是否有效。我可以把“www.myurlofjustice.com”这样做,并且这样做会返回“TRUE”,因为理论上它仍然会打开一个链接。你需要像在'PravatMaskey'的答案中那样检查HTTP状态响应。 – Popeye 2013-12-27 14:36:39

+0

不会。它返回'FALSE'。我现在就测试它! – skywinder 2013-12-27 14:42:20

+0

我刚刚测试了我提供的URL,如果你做了[[UIApplication sharedApplication] openURL:@“www.myurlofjustice”];'它实际上把我带到谷歌并作为搜索参数输入。那么你如何处理这个问题呢? – Popeye 2013-12-27 14:47:05