2017-08-01 55 views
0

這裏是我的代碼示例:NSURLSession如何檢索只有標題?

- (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只有所有的標題。

+0

你可以嘗試一個HTML解析器(有幾個庫)或'NSRegularExpression'和基準兩種解決方案。 – nathan

+0

看看這個:https://www.raywenderlich.com/14172/how-to-parse-html-on-ios。這可能會幫助你 – 3stud1ant3

+0

如果該網站的Web API以XML或JSON響應,我顯然會更好。否則,它只是更多的自定義/複雜的解析,如果他們更改頁面的HTML代碼,您可能需要重做它。 – Larme

回答

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

+0

這是非常骯髒的解決方案,但它的工作原理。謝謝。 我只是說,而不是 「的NSLog」 這個代碼行: 「爲(在arrTitles的NSString *標題){ 如果([標題rangeOfString:@」 蘋果觀察「。位置== NSNotFound){ }其他{ [titleWatches addObject:title]; } }「 現在它只輸出需要的標題。 –