Analysis of HTML tag by IOS and some holes in development

Time:2020-12-3

Opening

After reading the update date, I haven’t written a short book for a long time. I often have friends commenting at the bottom of the article. When I see what I wrote, it’s still a little useful. Encourage me to keep going, ha ha. Today, we mainly write about how to parse HTML tags in IOS. The commonly used data returned from the background is usually in JSON format. But sometimes, if we receive an HTML tag, what should we do with it? Let’s talk about it today.

text

When I got the background data two days ago, I got such a return message

"Congratulations on getting the cash reward of RMB 8.1 < / font >"

The simple display of the returned data on the label suddenly became interesting. The background said that it was to make it easier to handle the returned content when the product was changed. This reason is very strong.

But as a developer, how do we deal with it? First of all, let’s take a look at Android’s processing methods. Android has a systematic method for dealing with people who are still relatively rude, as follows:

How to deal with the IOS side? We can use WebView, the attributedstring attribute of label, or simply and roughly split the string, and then remove the HTML tag, then process and listen to it. However, it is a method, and the methods that can solve the problem are all good methods. Let’s put the main code of the most crude method (the other methods are in the The method to remove HTML tags is as follows:

//Filtering tags in the background return string
- (NSString *)flattenHTML:(NSString *)html {
  
  NSScanner *theScanner;
  NSString *text = nil;
  
  theScanner = [NSScanner scannerWithString:html];
  
  while ([theScanner isAtEnd] == NO) {
    // find start of tag
    [theScanner scanUpToString:@"<" intoString:NULL] ;
    // find end of tag
    [theScanner scanUpToString:@">" intoString:&text] ;
    // replace the found tag with a space
    //(you can filter multi-spaces out later if you wish)
    html = [html stringByReplacingOccurrencesOfString:
        [NSString stringWithFormat:@"%@>", text]
                        withString:@""];
  }
  MidStrTitle = html;
  return html;
}

In this way, we will deal with HTML tags. The problem is, if we want to deal with a lot of HTML tags, how should we deal with them? This is the purpose of this article.

Tfhpple Library

If we want to get the content of a tag in the following HTML source code, part of the source code is as follows, only the content of the tag is put here

< title > statement about app

</head>
<body>
<h3>Statement on app</h3>

<p>It's just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test</p>

<p>It's just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test</p>

<h3>Contact us</h3>

<p>If you have any problems or new ideas when using the app, you can contact us</p>

<ul>
<li>It's just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test</li>
<li>E-mail: xxxxxxxxxxxxxxxxxxxxxxxxxx</li>
<li>phone: xxxxxxxxxxxxxxxxxx</li>
</ul>


<h3>Thank you</h3>

<p>First of all, thank you for your support and encouragement to our company</p>

<p>It's just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test</p>

<h3>Copyright notice</h3>

<p>It's just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test just a test</p>
</body>
</html>

Here, if I want to get the content of a certain tag, I will use the library we introduced today.

Configuration of environment

Import static library

Then add the imported static library to the path of the file

Then import the TFHP ple library.

Use method 1, simple tag form value method

Direct code

NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
    NSString *filePath =[resourcePath stringByAppendingPathComponent:@"about.html"];
    NSData *data =[[NSData alloc]initWithContentsOfFile:filePath];
    NSString *result = [[NSString alloc] ini tWithData:data encoding : nsutf8stringencoding]; // data is converted into a string for printing, which is not garbled
    NSLog(@"------%@",result);
  
    TFHpple *Hpple = [[TFHpple alloc]initWithHTMLData:data];
  
    //Test 1: get a simple title
    Nsarray * array = [HP searchwithxpathquery: @ "// Title"]; // get the title of title
  
    for (TFHppleElement *HppleElement in array) {
  
      Nslog (@ "test 1's purpose tag content: -% @", HppleElement.text );
      
    }

We got the local one first about.html The file is then converted to data, and then converted to the following figure with utf8 encoding

The upper part is the original tag of the HTML file, and the lower part is the content with the tag “title” we go to. So we get what we want

Usage 2: tag content value with its own attribute

The HTML file above is inconvenient due to the limitation of its content. For example, the source code of HTML tag we use is as follows:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>hello</title>
</head>
<body>hello world
<span>
</span>
Unordered list
<ul type="disc">
  <li>Apple</li>
  <li>Fruit</li>
  <li>Peach</li>
</ul>
<ul type="circle">
  <li>Apple 2</li>
  <li>Fruit 2</li>
  <li>Peach 2</li>
</ul>
</body>
</html>

What we want to get is the label content with the unordered list node attribute as the type attribute and the value as disc. Obviously, the above method can no longer meet our needs. The old rule is to start with the code:

//Test 2: get more details
  NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
  NSString *filePath =[resourcePath stringByAppendingPathComponent:@"first.html"];
  NSData *data =[[NSData alloc]initWithContentsOfFile:filePath];
  
  NSString *result = [[NSString alloc] ini tWithData:data encoding : nsutf8stringencoding]; // data is converted into a string for printing, which is not garbled
  NSLog(@"------%@",result);
  
  TFHpple *Hpple = [[TFHpple alloc]initWithHTMLData:data];
  NSArray *array =[Hpple searchWithXPathQuery:@"//ul"];
  
  for (TFHppleElement *HppleElement in array) {
    
    if ([ HppleElement.attributes [@ "type"] isequaltostring: @ "disc"]) {// find the array whose node attribute type attribute value is disc under UL tag
      
      NSArray *array2 = [HppleElement searchWithXPathQuery:@"//li"];
      
      for (TFHppleElement *HppleElement2 in array2) {
        
        Nslog (@ "test 2 purpose tag content: -% @", hppleelement2. Text);
      }
    }
  }

The use method focuses on the following judgment of if statement


 if ([HppleElement.attributes[@"type"]isEqualToString:@"disc"]) {
}

If there is content under this condition, according to the bool value, get the content labeled “Li” below and run the result as follows:

Some pits encountered in the project

We can’t finish after we take the label. If we have time, let’s write about some small problems we have encountered.

Custom keyboard

Custom keyboard is also an old problem. Due to different situations, we may need to define a fully customized keyboard to meet the needs of various exotic flowers. Recently, when I read the code, I found that different people write differently. Here I introduce a simpler method.

The inputview property of uitextfield is as follows:


kkeyboardView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320 ,260 )] ;
  kkeyboardView.backgroundColor = [UIColor lightGrayColor];
  [self setUpMyKeyBoard2];
  self.textfiled.inputView = kkeyboardView;

Create a view and use it as the inputview of uitextfield. At this time, you can completely customize the customized keyboard you want. Come here to talk about what you need on the keyboard.

Rolling problem of uiscrollview

The day before yesterday, my colleague said a strange problem. He said that lazy loading had been written, layout had been done, offset had been set, and other pages had been done well. The page’s rolling attempt suddenly stopped moving. The old driver also rolled over and loved to see it, but how to deal with the problem.


-(void)viewDidLayoutSubviews
{
  _BaseScore.contentSize = CGSizeMake(SCREEN_WIDTH, 568.0 - 44); 
}

After a series of twists and turns, he was given this method. After writing the offset in this method, he could not help but say that he was old and found his memory was getting worse and worse. Ha ha, a group of such colleagues were really happy with their work.

Postscript

Today’s main introduction is just so much, I hope it can help the small partners in need. If I have time, I will write it next time. For the use of the project, the merchant side generates QR code collection, the client side scans QR code payment, as well as a series of QR code related functions, such as regular refresh, status judgment, scanning QR code to generate invitation code. There is a wrong place to write welcome pointed out, God light spray, ha ha.

Add:Two simple methods are added

Attributedstring attribute of label


NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[h5str dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
[selflab setAttributedText:attrStr];

Using web view

_webView = [[UIWebView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
NSString *html_ str = [NSString stringWithFormat:@"<div style=' color:red '> 666666 < / div > test% @ ", @" fresh wind makes waves ", @" 2020-01-00 "];
[self.webView loadHTMLString:html_str baseURL:nil];
[self.view addSubview:self.webView];

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.

Recommended Today

PHP 12th week function learning record

sha1() effect sha1()Function to evaluate the value of a stringSHA-1Hash. usage sha1(string,raw) case <?php $str = “Hello”; echo sha1($str); ?> result f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0 sha1_file() effect sha1_file()Function calculation fileSHA-1Hash. usage sha1_file(file,raw) case <?php $filename = “test.txt”; $sha1file = sha1_file($filename); echo $sha1file; ?> result aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d similar_text() effect similar_text()Function to calculate the similarity between two strings. usage similar_text(string1,string2,percent) case […]