Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if url is an image

I have following code:

NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray* matches = [detector matchesInString:[[imagesArray valueForKey:@"content"] objectAtIndex:indexPath.row] options:0 range:NSMakeRange(0, [[[imagesArray valueForKey:@"content"] objectAtIndex:indexPath.row] length])];

This result in the log:

<NSLinkCheckingResult: 0xa632220>{235, 75}{http://URL/wordpress/wp-content/uploads/2014/04/Digital-Board-2.png}
<NSLinkCheckingResult: 0xa64eb90>{280, 25}{http://www.w3schools.com/}

What I need is to check the links wether they contain an image. In this case the first link contain an image (PNG). The second doesn't. How can I do this?

like image 218
user3423384 Avatar asked Apr 20 '14 08:04

user3423384


2 Answers

You could get the NSURLs for them and compare the extensions against a list of image extensions. Something like this perhaps:

// A list of extensions to check against 
NSArray *imageExtensions = @[@"png", @"jpg", @"gif"]; //...

// Iterate & match the URL objects from your checking results
for (NSTextCheckingResult *result in matches) {
    NSURL *url = [result URL];
    NSString *extension = [url pathExtension];
    if ([imageExtensions containsObject:extension]) {
        NSLog(@"Image URL: %@", url);
        // Do something with it
    }
}
like image 135
Alladinian Avatar answered Oct 05 '22 22:10

Alladinian


Based on this answer you could use HTTP HEAD request and check content type.
List of possible content types for images is here.

Code sample:

- (void)executeHeadRequest:(NSURL *)url {
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"HEAD"];
    [NSURLConnection connectionWithRequest:request delegate:self]
}

// Delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSHTTPURLResponse *response = (NSHTTPURLResponse *)response;
    NSString *contentType = [response.allHeaderFields valueForKey:@"Content-Type"];
    // Check content type here
}
like image 43
Vlad Papko Avatar answered Oct 05 '22 23:10

Vlad Papko