IOS uiwebview url Blocker

Source: Internet
Author: User

Http://www.cocoachina.com/ios/20150626/12161.html

This translator: Candeladiao, Original: URL filtering for UIWebView on the IPhone
Description: When the translator is doing the app development, because the page's JavaScript file is relatively large resulting in slow loading, so you want to package JavaScript files in the app, when the UIWebView need to load the script from the app to read locally, However, UIWebView does not support loading local resources. Finally, from the following find a solution, the first translation, inevitably wrong, we have a lot of advice.

ICab Mobile, a Web browser for an iOS platform, implements an interception manager to filter ads and other things on the page. It has a simple list of URL filtering rules (usually maintained by the user), and when the page contains resources (Pictures, JS, CSS, etc.), the URL of the file is present in the list of rules, and the resource is not loaded.

But looking at the API of the UIWebView class, we will find that we have no way to know what resources UIWebView are loading, and, worse, when you want to filter out some resource files, there is no way to force UIWebView not to load these files,

The interceptor seems unlikely to happen.

Of course there is a solution, otherwise this document will be no use of eggs.

As stated above, implementing interceptors cannot rely on UIWebView, because UIWebView does not provide any useful APIs.

For all requests to UIWebView, to find a pointcut that interrupts all HTTP requests, we need to look at Cocoa's URL Loading system, because UIWebView uses the URL Loading system to fetch data from the Web side. The pointcut we need Nsurlcache class is part of the URL Loading system. Although the iOS system does not cache any data on disk at this time (the iOS system version may be different later), the Nsurlcache managed cache data is usually empty until UIWebView starts to load, but UIWebView will still detect if the requested resource file exists in the cache. So all we need to do is inherit the Nsurlcache and reload its method:

1 - (NSCachedURLResponse*)cachedResponseForRequest:(NSURLRequest*)request

This method is called when UIWebView requests all resources. Because we just need to determine in this method whether the requested URL is what we want to intercept. If yes, create a fake response with no content, or simply call the Super method.

Here are the implementation details:

1. Inheritance Nsurlcache:

FilteredWebCache.h:

1234 @interface FilteredWebCache : NSURLCache@end

Primary code for subclasses

FILTEREDWEBCACHE.M:

1234567891011121314151617181920212223 #import "FilteredWebCache.h"#import "FilterManager.h"@implementation FilteredWebCache- (NSCachedURLResponse*)cachedResponseForRequest:(NSURLRequest*)request{    NSURL *url = [request URL];    BOOL blockURL = [[FilterMgr sharedFilterMgr] shouldBlockURL:url];    if(blockURL) {        NSURLResponse *response =              [[NSURLResponse alloc] initWithURL:url                                        MIMEType:@"text/plain"                           expectedContentLength:1                                textEncodingName:nil];        NSCachedURLResponse *cachedResponse =              [[NSCachedURLResponse alloc] initWithResponse:response                             data:[NSData dataWithBytes:" "length:1]];        [superstoreCachedResponse:cachedResponse forRequest:request];        [cachedResponse release];        [response release];    }    return[supercachedResponseForRequest:request];}@end

First determine if the URL needs to be intercepted (judged by the Filtermanager class implementation, the class implementation is not listed here). If necessary, create a non-content response object and present it in the cache. One might think that just returning a fake response object is enough, and there is no need to cache it. However, this will cause the app to crash because the response object is released by the system. I don't know why this might be a bug in iOS (Mac OS X 10.5.x has the same problem, and there are no problems with 10.4.x and earlier systems), or it could be a dependency between the URLs Loading system internal classes. So we cache the response object first. Make sure that all responses are real in the cache, which is what iOS wants and, most importantly, not crash.

Update: Because a fake response is initialized with a size greater than 0, it is also necessary to look at the node cache.

2. Create a new cache:

Next you need to create a new cache and tell the iOS system to use the new cache instead of the default, so that the above code is called when the URL Loading system detects the resource cache. This should be done in front of any UIWebView start loading page, which should obviously be placed when the app starts:

12345678 nsstring *path = . // the path to the cache file nsuinteger disccapacity = 10*1024*1024; nsuinteger memorycapacity = 512*1024; filteredwebcache *cache =        [[filteredwebcache alloc] initwithmemorycapacity: memorycapacity Code class= "JS Spaces" >                               diskcapacity: disccapacity diskpath:path]; [nsurlcache setsharedurlcache:cache]; [cache release];

You need to provide a cache storage path here. The cache file is automatically generated by the Nsurlcache object, and we do not need to create the file beforehand, but to define where the cache file will be stored (must be in the application "sandbox", such as the "TMP" directory or the "Document" directory)

This is all the content that implements the UIWebView URL-based request filtering, and it doesn't look complicated.

Note: If the filter rule changes during app operation, you need to remove the fake response from the cache. Nsurlcache provides a Delete method, so this is not a problem. If the filtering rules do not change, you do not need to care

IOS uiwebview url Blocker

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.