Loading local and remote content into UIWebView (Xcode for iOS)

Dropping a UIWebView into an app can be a versatile way to view local (X)HTML pages, PDFs and Word Docs among other file types. To add one to your ViewController drag and drop it from the objects menu, then control click from the UIWebView to your ViewController.h file to create the IBOutlet.

Having done this, in the ViewController.m file within -(void)viewDidLoad: use the following code:
[remoteWebContent loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.gylphi.co.uk/"]]];


And for local content:
[localWebContent loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Text/page3" ofType:@"xhtml" inDirectory:@"Brochure/"]isDirectory:NO]]];


The second chunk of code - referencing an instance of UIWebView called localWebContent - will access a file called page3.xhtml in a folder Brochure/Text/ and as long as all the CSS and images are within the brochure folder or within a folder that is within this then all will work as expected. (Add the actual content and folders from your desktop using File - > Add files to " " ... and selecting "create folder references for any added folders". This will keep things nicely organised and you can add files to the folders external to Xcode at any time.)

Note: The lines of code for the remote web pages are the same method uploaded to YouTube by OToph while the local content code I composed from trial and error paired with a variety of sources.


Comments