NSURLSession如何只检索标题?

时间:2017-08-01 15:37:15

标签: ios objective-c nsurlsession nsurlsessiondatatask

以下是我的代码示例:

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

它返回:

data structure

我想检索并NSLog只有所有标题。

1 个答案:

答案 0 :(得分:1)

尝试以下代码,您将获得所需的输出。

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

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

enter image description here