Develop HYBRID apps using UIWebView (2)

In hybrid applications, caching is tricky.

Objective-c has a cached class NSURLCache, which is officially given The explanation is:It provides a composite in-memory and on-disk cache. In other words, when the application is closed, the cache is invalidated. In order to make persistent storage of data that does not change frequently, you need to implement it yourself.


Thinking:

< /span>UIWebview stores the page and its corresponding data locally every time it requests a URL. When the user requests the data again, directly load the data in the disk.


Project :

1. When the URL is requested for the first time, the Save the HTML file locally; parse the file to find out the links to js, ​​css, and pictures, and download them locally; replace the links to the pictures and other resources in the HTML file with the local path.

As in the example, the link contains the following link:< /span>

They are divided into The three categories start with link, script, and img, and they can be easily extracted through a regular expression.

NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"<(img|link|script|a)[^>]+?(src|href)=[\"']?([^>'\"]+ )[\"']?" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];NSArray* result = [regex matchesInString:htmlString options:NSMatchingReportCompletion range:NSMakeRange(0, htmlString.length)];

result is a list containing the links to the above. After finding each src, classify them, and then download these files according to different types and record them in the local address. Then put < span style="font-size:14px">The network path of the HTML file is replaced with the local path.


< /span>

2. When the URL is requested again, UIWebview loads the local path , The response speed is very fast.

[_webView loadHTMLString:loade dString baseURL:[NSURL fileURLWithPath:filePath]];


Conclusion:

The specific method is in the demo given later. Of course, there are still many details that can’t be shown one by one, but it will be clearer if you look at the source code. The program also needs to be optimized, welcome to point out.


demo download

Leave a Comment

Your email address will not be published.