尝试从NSString中提取图像URL

时间:2016-01-02 11:57:27

标签: objective-c nsstring rss nsxmlparser nsrangeexception

我正在尝试为iOS做一个RSS Feed应用程序,我正在尝试从xml文件的描述标记中获取图像URL(RSS Feed)

这是我目前的代码:

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);
    }
}

我的应用程序崩溃了,我在崩溃日志中得到了这个:

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

这是什么意思?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您在此代码中使用appendString:的原因是所提供的数据可能不完整(由于缓冲等处理过程中)。在标记的解析完成之前,您不应该尝试处理内容。

您所看到的是rangeOfString:来电与任何内容都不匹配,并返回位置为NSNotFound的范围。当您尝试使用它时,您将获得索引异常。

您应该将代码更改为在标记完成处理时运行,并防止找不到您正在查找的子字符串。

答案 1 :(得分:-1)

这可能会对您有所帮助:

- (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;
}