2011-05-15 19 views
7

Tengo un for-loop que actualmente se repite 4 veces.Objective-C - Comprobando si existe 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]; 
    } 

Como se puede ver la URL tiene un dígito en lo que consiguen incrementa en 1 cada bucle para crear un nuevo URL en la siguiente imagen será. Sin embargo, la cantidad de imágenes en el servidor no será necesariamente 4, podría ser mucho más o incluso menos. Mi problema es este, ¿hay alguna manera de verificar si hay una imagen almacenada en la URL? Y si no es así, rompa el ciclo y continúe con la ejecución del programa.

Gracias,

Jack

+0

posible duplicado de [¿Cómo verificar si existe un archivo en una URL específica?] (http://stackoverflow.com/questions/2021391/how-to-check-if-a-file-exists-at-particular-url) – zoul

Respuesta

16

Aquí es idea consultar con respuesta 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 
} 

o

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

pero será lento. lo que mi sugerencia es, si está utilizando su propio servidor web, entonces, puede enviar toda la información de la imagen inicialmente. Estoy seguro de que está haciendo este trabajo en annonymous u otro sitio web :) Avísame si le ayuda o no

-2

Aquí es forma más sencilla de comprobar si URL es válido:

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

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

This no verificará si la URL es válida. Podría poner '' www.myurlofjustice.com '' y hacerlo de esta manera devolvería 'VERDADERO' porque en teoría todavía abre un enlace. Debe verificar la respuesta del estado HTTP como en la respuesta de 'PravatMaskey'. – Popeye

+0

No. Devuelve 'FALSE'. ¡Lo probé ahora mismo! – skywinder

+0

Acabo de probar la url que proporcioné y si lo hace '[[UIApplication sharedApplication] openURL: @" www.myurlofjustice "];' real me llevó a google e ingresé eso como los parámetros de búsqueda. Entonces, ¿cómo puedes manejar esto? – Popeye

Cuestiones relacionadas