Dr_Mom
Dr_Mom

Reputation: 63

NSURLSession how to retrieve only titles?

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.

Upvotes: 0

Views: 62

Answers (1)

Harshal Shah
Harshal Shah

Reputation: 427

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

Upvotes: 1

Related Questions