Search code examples
iphoneiossdwebimage

how can i check if NSUrl is a valid image url?


I'm using SDWebImage library and I have this code:

     [cell.imgLogo setImageWithURL:[NSURL URLWithString:[item objectForKey:@"s_logo"]]         placeholderImage:[UIImage imageNamed:@"default.png"]];

I have tweak the library SDWebImage a little bit to ignore empty string or a NSUrl with empty string in method downloadWithURL: delegate: options: userInfo::

     if ([url isKindOfClass:NSString.class])
     {
         if ([(NSString *)url length] > 0) {
              url = [NSURL URLWithString:(NSString *)url]; 
         } else {
              return;
         }
    }
    else if (![url isKindOfClass:NSURL.class])
    {
         url = nil; // Prevent some common crashes due to common wrong values passed like NSNull.null for instance
    }
    else if ([url isKindOfClass:NSURL.class]) {
         if ([[url absoluteString] length] > 0) {
              //valid url
         } else {
             return;
         }
     }

So now it works with empty string and just to display its default image but the problem is when it comes to a string that is not an image url like:

     http://beta.xxxxxxx.com/gangnamwe?to=boko

It displays nothing, it removes the placeholder image and displays nothing.

So how will I identify a valid image url? or is there any better work around for this?

Your help are much appreaciated.


Solution

  • you can check after getting NSData from NSURL . You can use GCD to download data

    here is an example i created which save your image in photo library.

    dispatch_async(dispatch_queue_create("com.getImage", NULL), ^(void) {
    
            NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRKII9COB-hvMef4Zvb9XYVbXKDFZHJAHwwzzGyMiy_b-q65GD43Chd37jH"]];
            UIImage *image=[UIImage imageWithData:data];
            if (image==nil) {
                //yourImageURL is not valid
                image=[UIImage imageNamed:@"placeholder.png"];
            }
            else{
    
                //yourImageURL is valid
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
                    //show your image
                });
    
            }
    
        });