Using Nsurlprotocol to implement UIWebView offline caching

Source: Internet
Author: User
Tags http redirect

http://blog.csdn.net/youcanping2008/article/details/9240487

Search solution found Rob Napier's blog: Drop-in offline caching for UIWebView (and Nsurlprotocol) This article introduces a simple implementation of UIWebView offline caching using Nsurlprotocol, and you can download the demo code on GitHub.

Rob believes that both the "Mknetworkkit" and "Afcache" implementations of the cache are too complex, and what he wants is a simple mechanism:

1. You use the UIWebView point to display a website with image embedding.
2, when your device online, you have a normal cache algorithm.
3. When your device is offline, you can display the last version of the page.

This demo has a very simple test: run the CNN.com once and then disconnect the network to see the data.

Existing solutions:

Matt Gallagher has some interesting ideas that are implemented using Nsurlcache subclasses, but Rob finds this to be unreliable, especially IOS5 's HTTP caching rules are complex, and in many cases you won't know if your cached data is valid if you don't access the server. In addition, some of the necessary material if not cached, then the first time when offline cache work is effective. (FAI: Nsurlcache realize offline reading a little bit more careful I have discussed some of the related issues)

Afcache is also considered to be a good solution (FAI: I will evaluate this open source library in detail when I have time, on the surface it is connection, Nsurlcache, Nsurlprotocol's comprehensive solution). The author did not pass the test in a short time, but the author of the Afcache also replied in the back of the article that he had adopted Rob's idea and had submitted the code to GitHub.

Key points:
1. Register your Urlprotocol as soon as possible (application:didfinishlaunchingwithoptions:).
2, Nsurlprotocol is the handler of Nsurlconnection. Each request from Nsurlconnection will facilitate all protocols and ask if you can handle the request (Caninitwithrequest:). If this protocol returns Yes, the first protocol that returns YES will handle the connection. Protocols traversal is reversed, that is, the last registered protocol will be prioritized.
3. When your handler is selected, connection will call –> InitWithRequest:cachedResponse:client: Immediately after that, –>startloading will be called. Then you need to be responsible for the callback: –>urlprotocol:didreceiveresponse:cachestoragepolicy:, some will call: –>urlprotocol:didloaddata:, and will eventually call –>urlprotocoldidfinishloading:. Have you found these methods andNSURLConnectionDelegate's approach is very similar-it's no coincidence!
4, in the case of online, Rncachingurlprotocol is only responsible for forwarding the request to a new nsurlconnection, and copy a result to the original connection. Offline, Rncachingurlprotocol loads the previous results from the disk and sends the data back to the connection. The entire process is only a paltry 200 lines of code (not including reachability).
5, there is also an interesting question, is that when Rncachingurlprotocol created a new nsurlconnection, that is, the new connection will find a handler. If Rncachingurlprotocol said he could handle it, it would be a dead loop. How to solve it? Flag this request by adding a custom HTTP Header (X-rncache), telling Rncachingurlprotocol not to process the request again.
6, it can respond to all connection, so you may need to modifycanInitWithRequest:来Select the data you want to cache.

In addition: caching of concurrent requests or complex network requests use Mknetworkkit (We also use this class library in a project, very light and fast is a good alternative to ASI).

To summarize:
This technique is not intended to replace Afcache, Mknetworkkit, but rather to solve a single, simple problem (and of course it can solve complex problems through complex implementations). NSURLProtocolis very powerful, and Rob has used it to monitor network traffic (such as several proxyurlprotocol classes in Pandoraboy). It's well worth adding to your toolbox.

Instance code download: Https://github.com/rnapier/RNCachingURLProtocol

See the class file in the demo: RNCachingURLProtocol.m .

Be sure to look at the workaround for redirect that Nick Dowell replied to in the comments: (Code to fix HTTP redirect handling:https://gist.github.com/1885821)

1234567891011121314 (nsurlrequest *connection: (nsurlconnection  *) connection willsendrequest< Span class= "o" >: (nsurlrequest * ) request redirectresponse: (nsurlresponse *response { if ([response Iskindofclass:[nshttpurlresponse class]] ){nshttpurlresponse *httpresponse = (nshttpurlresponse *) response; if ([httpresponse statusCode] = = 301 | | [httpresponse statusCode] = = 302) {nsmutableurlrequest *mutablerequest = [request mutablecopy]; [mutablerequest seturl:[nsurl urlwithstring:[[ HttpResponse allheaderfields] objectforkey:@ "Location" ]] ; request = [mutablerequest copy]; [self- client] urlprotocol: Self wasredirectedtorequest: Request redirectresponse: Response]; }}return request; }

If you are interested, you can read this article: Nsurlcache to realize offline reading

Using Nsurlprotocol to implement UIWebView offline caching

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.