0

Here is an example of my code:

    - (void)displayURL {

    NSString *myUrlString = @"https://3docean.net/search/apple%20watch?page=1";
    NSURL *myUrl = [NSURL URLWithString:myUrlString];
    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:myUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSString *htmlString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@", htmlString);

        } else {
            NSLog(@"error = %@", error.localizedDescription);
        }
    }];
    [dataTask resume];
}

It returns:

data structure

I want to retrieve and NSLog only all titles.

nathan
  • 9,329
  • 4
  • 37
  • 51
Dr_Mom
  • 63
  • 8
  • You could try a HTML parser (there are several libraries) or `NSRegularExpression` and benchmark both solutions. – nathan Aug 01 '17 at 15:48
  • Check out this:https://www.raywenderlich.com/14172/how-to-parse-html-on-ios. This may help you – 3stud1ant3 Aug 01 '17 at 16:00
  • I would clearly be better if that website has an Web API responding in XML or JSON. Else, it's just more custom/complicate parsing, and if they change their HTML code for the page, you may have to redo it. – Larme Aug 02 '17 at 08:01
  • Yes, I understand how to figure out the solution using hpple parser, for example. But I want to know, how to parse web pages using only NSURL native methods if it possible. – Dr_Mom Aug 02 '17 at 10:02

1 Answers1

1

Try below code and you will get your desired Output.

NSString *myUrlString = @"https://3docean.net/search/apple%20watch?page=1";
NSURL *myUrl = [NSURL URLWithString:myUrlString];
NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *dataTask = [session dataTaskWithURL:myUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSString *htmlString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@", htmlString);

    NSArray *urlComponents = [htmlString componentsSeparatedByString:@"title="];

    NSMutableArray *arrTitles = [[NSMutableArray alloc]init];
    for (NSString *str in urlComponents)
    {
        NSString* newNSString =[[[[str componentsSeparatedByString:@"\""]objectAtIndex:1] componentsSeparatedByString:@"\""]objectAtIndex:0];

        [arrTitles addObject:newNSString];
    }

    NSLog(@"arrTitles : %@",arrTitles);

}];
[dataTask resume];

This is my Output which contains all the "title" values.

enter image description here

Harshal Shah
  • 427
  • 3
  • 5
  • It's pretty dirty solution, however it works. Thanks. I just added instead "NSLog" this lines of code: "for (NSString *title in arrTitles) { if ([title rangeOfString:@"Apple Watch"].location == NSNotFound) { } else { [titleWatches addObject:title]; } }" And now it outputs only needed titles. – Dr_Mom Aug 03 '17 at 12:00