NSURLSession 如何只检索标题?

NSURLSession how to retrieve only titles?

这是我的代码示例:

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

它returns:

我只想检索 NSLog 所有标题。

试试下面的代码,你会得到你想要的输出。

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];

这是我的输出,其中包含所有 "title" 值。