Sunday 15 January 2012

iOS: Open UIWebView with local javascript files -


I want to open a website in a UIWebView , but I want to load Wan't Javascript files from the app's document folder (due to bandwidth) is this possible?

Yes, you'll need to create a custom NSURLProtocol as in this post : Make a suitable check in canInitWithRequest:. according to the sample to your JavaScript with the appropriate content type

Update:

A quick shot at a sample implementation:

  @interface LocalJSURLProtocol: NSURLProtocol @end @implementation LocalJSURLProtocol + (bool) canInitWithRequest: (NSURLRequest *) request {return [request.URL.scheme caseInsensitiveCompare: @ "http"] == Ansordedsm & amp; Amp; [Request.URL.lastPathComponent is Suffix: @ "js"]); } + (NSURLRequest *) canonicalRequestForRequest: (NSURLRequest *) Request {Refund Request; } - (zero) start application {NSRR request} request = self. request; NSURLResponse * response = [[NSURLResponse alloc] initWithURL: [Request URL] MIME type: @ "text / javascript" expectedContentLength: -1 textEncodingName: nil]; NSString * localFilePath = [[NSBundle main bundle] pathForResource: @ "sample.js" type: zero]; NSDTa * Data = [NSDTATA DataWith ContentFile: LocalFilePath]; [Self. Client URL Protocol: Did It Own Receptance: Response Cash Storage Policy: NSURLCacheStorageNotAllowed]; [Self. Client URL Protocol: Automatically Loaded Data Data]; [Self. Ethical URLProtocolDidFinish Loading: Self]; } - (void) stopLoading {} @end   

and register the protocol [ NSURLProtocol registerClass: [LocalJSURLProtocol class]]; Before starting to load. This will block the request in your UIWebView and you will have the chance to inject your Javascript code for the request file.

No comments:

Post a Comment