0

Im having some trouble findig a way to validate a url on my app.
My intention is to load a URL and at the same time see if other webpage exist for example.

Load http://mysite.com/folder1/1.pdf
validate http://mysite.com/folder1/2.pdf
if folder1/2.pdf exists then load it, else validate /folder2/1.pdf

so far im loading the first pdf like this in order to be able to change the pdf number and the folder:

int numpag = 1;
NSString *baseUrl =@"http://www.cronica.com.mx/iphone/pdf_iphone/";
[pdfView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[baseUrl stringByAppendingFormat:@"folder1/%d.pdf", numpag]]]];

Thanks so much in advance!

Ponchotg
  • 1,195
  • 1
  • 14
  • 25

3 Answers3

4

how about this:

+ (BOOL)isValidURL:(NSURL*)url
{
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    NSHTTPURLResponse *res = nil;
    NSError *err = nil;
    [NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&err];
    return err!=nil && [res statusCode]!=404;
}

let me know if it works for you!

(keep in mind that this is a synchronous request and should not be executed on the main thread)

cwimberger
  • 71
  • 1
  • Hi: tell me if im doing something wrong: `- (void)isValidURL:(NSURL*)url { NSLog(@"launched with site %@\n",url); NSURLRequest *req = [NSURLRequest requestWithURL:url]; NSHTTPURLResponse *res = nil; NSError *err = nil; [NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&err]; BOOL errono = err!=nil && [res statusCode]!=404; NSLog(@"gives error? %@", (errono ? @"YES" : @"NO")); }` i allways get response NO on the "gives error" LOG the url is really not valid and tried allso with a valid one and same THANKS – Ponchotg Mar 30 '11 at 16:28
  • Hi again i changed the code a little in my if, instead of using the "bool" i'm using another variable that just gives me the error code and its working beautlifully! – Ponchotg Mar 30 '11 at 16:37
  • Do not use the error (err in this snippet) to determine wether an error happened, but the return value of the called method (nil or NO means error). There is no guarantee that err is nil, even if the method worked just fine. – Johan Kool Apr 13 '11 at 16:48
  • If you are using threads (not sendSynchronousRequest:) then look at the answer by "unforgiven3" here: http://stackoverflow.com/questions/917932/retrieve-httpresponse-httprequest-status-codes-iphone-sdk – Gik Jan 10 '13 at 13:44
0

This approach is NOT correct, You should avoid Synchronous calls as they are blocking. Apple says: simply try and wait down to wait for response.

ingconti
  • 10,876
  • 3
  • 61
  • 48
0

I had to change the line:

return err!=nil && [res statusCode]!=404;

to

return err==nil && [res statusCode]!=404;

for the correct Bool return. The error should remain nil.