当我从URL获取文本时,如何删除这些行?

时间:2014-09-02 17:55:50

标签: ios iphone xcode nsdata nsurl

我尝试从网址获取一些文字并将其放在UITextView中。 这是我在ViewController

中的代码
NSString *urlString = @"http:/...";
NSError  *error     = nil;
NSData   *dataURL   = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString] options:kNilOptions error:&error];

if (error)
    NSLog(@"%s: dataWithContentsOfURL error: %@", __FUNCTION__, error);
else
{
    NSString *result = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
    NSLog(@"%s: result = %@", __FUNCTION__, result);

    // if you were updating a label with an `IBOutlet` called `resultLabel`, you'd do something like:

    self.mytextview.text = result;
}

现在模拟器在我的视图中显示了该文本: enter image description here

对不起,文字是德语:)

现在我该如何隐藏或删除那个html,head,body等?

2 个答案:

答案 0 :(得分:1)

您应该使用UIWebView并加载您的html文字,如下所示:

[_webView loadHTMLString:result baseURL:nil];

答案 1 :(得分:1)

它显示为这样,因为您正在下载HTML格式的PHP文件的内容。

您可以创建一种方法来查找&删除“<”之间的每个HTML标记和“>”

- (NSString*)stringByRemovingHTMLtags:(NSString*)string {
  NSRange range;
  while ((range = [string rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
    string = [string stringByReplacingCharactersInRange:range withString:@""];
  return string;
}

然后在UITextView中设置文本,如下所示:

 self.mytextview.text = [self stringByRemovingHTMLtags:result];

编辑:要获取<p>标记的内容,请使用以下方法:

- (NSString*)getPtagContentFromString:(NSString*)htmlString {
    NSRange startRange = [htmlString rangeOfString:@"<p>"];
    if (startRange.location != NSNotFound) {
        NSRange targetRange;
        targetRange.location = startRange.location + startRange.length;
        targetRange.length = [htmlString length] - targetRange.location;
        NSRange endRange = [htmlString rangeOfString:@"</p>" options:0 range:targetRange];
        if (endRange.location != NSNotFound) {
            targetRange.length = endRange.location - targetRange.location;
            return [htmlString substringWithRange:targetRange];
        }
    }
    return nil;
}

然后在UITextView中设置文本,如下所示:

 self.mytextview.text = [self getPtagContentFromString:result];