Search code examples
iosiphonexcodensdatansurl

How to delete that rows, when i get text from URL?


i try to get some text from an URL and put it out in a UITextView. Thats my code in the 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;
}

Now the simulator shows that text in my view: enter image description here

Sorry, the text is german :)

Now how can I hide or delete that html, head, body etc.?


Solution

  • It displays like this because you are downloading the content of that PHP file which is in HTML format.

    You can create a method to find & delete each HTML tag between "<" and ">"

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

    Then set your text in the UITextView like this:

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

    EDIT: In order to get the content of the <p> tag use this method:

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

    Then set your text in the UITextView like this:

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