0

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?

Ziph0n
  • 197
  • 1
  • 1
  • 7

2 Answers2

1

The reason you use appendString: in this code is that the data provided may be incomplete (due to buffering and such during processing). Until the parse of a tag is complete you shouldn't try to process the contents.

What you're seeing is that your rangeOfString: call doesn't match anything and returns a range with a location of NSNotFound. When you try to use that you get an index exception.

You should change your code to run when the tag has completed processing and to protect against not finding the substring you're looking for.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • You are right. I put my code elsewhere and it works now. Now I'm wondering where can I put my code to avoid this. Thanks! – Ziph0n Jan 02 '16 at 13:45
-1

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;
}
Hamza Ansari
  • 3,009
  • 1
  • 23
  • 25