objective-cnsstringrssnsxmlparsernsrangeexception

Trying to extract an image URL from an NSString


I'm trying to do an RSS Feed application for iOS and I'm trying to get the image URL from the description tag of the xml file (of the RSS Feed)

Here's my current code:

static NSMutableString *title;
static NSMutableString *linkPost;
static NSMutableString *descriptionPost;
static NSString *element;

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

    if ([element isEqualToString:@"title"]) {
        [title appendString:string];
    } else if ([element isEqualToString:@"link"]) {
        [linkPost appendString:string];
    } else if ([element isEqualToString:@"description"]) {
        [descriptionPost appendString:string];
        NSString *imgURL = descriptionPost;
        imgURL = [imgURL substringFromIndex:[imgURL rangeOfString:@"src="].location+[@"src=" length]+1];
        imgURL = [imgURL substringToIndex:[imgURL rangeOfString:@"alt="].location-2];
        NSLog(@"log: imgURL = %@",imgURL);
    }
}

My application crash and I get this in the crashlog:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSCFString substringFromIndex:]: Index 9223372036854775812 out of bounds; string length 1'

What does that mean? How can I fix this?


Solution

  • This may help you:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        NSString *description = @"<p>The post <a rel=\"nofollow\" href=\"http://www.raywenderlich.com/123606/video-tutorial-adaptive-layout-part-8-conclusion\">Video Tutorial: Adaptive Layout Part 8: Conclusion</a> appeared first on <a rel=\"nofollow\" href=\"http://www.raywenderlich.com\">Ray Wenderlich</a>.</p>";
    
        NSString *url = [self extractFromString:description start:@"href=\"" end:@"\">"];
        NSLog(@"%@",url);
    
    
    }
    
    -(NSString*)extractFromString:(NSString*)string start:(NSString*)start end:(NSString*)end{
    
        NSRange r1=[string rangeOfString:start];
        NSRange  r2 = [string rangeOfString:end];
        NSRange rSub = NSMakeRange(r1.location + r1.length, r2.location - r1.location - r1.length);
    
        NSString *extractedString=[string substringWithRange:rSub];
        return extractedString;
    }