Getting the second paragraph in html - iOS

193 Views Asked by At

I am making an app which will get text from a website I have got this code so far

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURL *URL = [NSURL URLWithString:@"http://rss.cnn.com"];
    NSData *data = [NSData dataWithContentsOfURL:URL];

    // Assuming data is in UTF8.
    NSString *string = [NSString stringWithUTF8String:[data bytes]];
    show.text = string;


    NSString *webString = show.text;
    NSScanner *stringScanner = [NSScanner scannerWithString:webString];
    NSString *content = [[NSString alloc] init];
    while ([stringScanner isAtEnd] == NO) {
        [stringScanner scanUpToString:@"<p>" intoString:Nil];
        [stringScanner scanUpToString:@"</p>" intoString:&content];


        show.text = content;
    }


}

As you can see I am trying to capture the paragraph and that has worked it pulls the first paragraph from the website, when I see all the html code I see there are more than one <p> / paragraphs like it has a <p> (some text) </p> (Some other code) <p> (some text) </p>

My app only captures the first paragraph how can I make it so the app can capture the second paragraph as well? Thank you!

1

There are 1 best solutions below

3
On

You can do this by using regular expressions. Use following code,

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\<p>(.*?)\\</p>" options:NSRegularExpressionCaseInsensitive error:NULL];

NSString *webString = show.text;

NSArray *myArray = [regex matchesInString:webString options:0 range:NSMakeRange(0, [webString length])] ;

NSMutableArray *matches = [NSMutableArray arrayWithCapacity:[myArray count]];

for (NSTextCheckingResult *match in myArray) {
    NSRange matchRange = [match rangeAtIndex:1];
    [matches addObject:[webString substringWithRange:matchRange]];

    NSLog(@"%@", [matches lastObject]);
}