Objective-C - 检查URL是否存在

Jac*_*ins 7 arrays iphone url objective-c ios

我有一个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://photostiubhart.comoj.com/GalleryImages/%dstiubhart1.jpg", i];
        [myURLS addObject: [NSURL URLWithString:tempString]];
        [tempString release];
    }
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,URL中有一个数字,每个循环增加1,以创建下一个图像所在的新URL.但是,服务器上的图像数量不一定是4,可能更多甚至更少.我的问题是,有没有办法可以检查URL中是否存有图像?如果没有,打破循环并继续执行程序?

谢谢,

插口

Muj*_*key 17

以下是使用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
}
Run Code Online (Sandbox Code Playgroud)

要么

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

但它会很慢.我的建议是,如果您使用自己的网络服务器,那么,您可以最初发送所有图像信息.我确定你在匿名或其他网站上做这个工作:)让我知道它是否有帮助你