Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - display content from an html resource file or remote webpage in a webview

Tags:

ios

uiwebview

I am an iOS newbie. I want to have a function that loads the content from a local html resource file or a webpage depending on what is specified in a constant. How would I go about doing it? For eg, if I pass a file://... to the function or an http://... , it should render accordingly.

like image 826
Suchi Avatar asked Dec 20 '11 15:12

Suchi


People also ask

What is WKWebView in iOS?

A WKWebView object is a platform-native view that you use to incorporate web content seamlessly into your app's UI. A web view supports a full web-browsing experience, and presents HTML, CSS, and JavaScript content alongside your app's native views.

What is UIWebView in iOS?

What is UIWebView? UIWebView is a deprecated iOS user interface control in Apple's UIKit framework. It loads HTML files and web content into an app view, rendering them as they would appear in a browser window. See developer.apple.com/documentation/uikit/uiwebview.

Is WKWebView deprecated?

Since then, we've recommended that you adopt WKWebView instead of UIWebView and WebView — both of which were formally deprecated. New apps containing these frameworks are no longer accepted by the App Store.


1 Answers

You can easily load webpages like this:

NSURLRequest *request = [NSURLRequest requestWithURL:
   [NSURL URLWithString:@"http://stackoverflow.com"]] ;

[webView loadRequest:request] ;

For local files it depends on the location of the file on your device: For files in your main-bundle (= your project), you can use the same loadRequest function, but build the path differently:

NSString *localFilePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"] ;
NSURLRequest *localRequest = [NSURLRequest requestWithURL:
  [NSURL fileURLWithPath:localFilePath]] ;

[webView loadRequest:localRequest] ;

and if you want to load a html-string in your webView:

NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:bundlePath];

NSString *htmlString = [bundlePath pathForResource:@"index" ofType:@"html"] ;
[webView loadHTMLString:htmlString baseURL:baseURL];

and if your html-file resides in your documents folder of your application (for example a html-file you downloaded):

NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"index.html"];
NSURLRequest *documentsRequest = [NSURLRequest requestWithURL:
  [NSURL fileURLWithPath:path]] ;

[webView loadRequest:documentsRequest] ;
like image 195
notyce Avatar answered Sep 27 '22 19:09

notyce