Member-only story
Load Document files like .pfd,.txt,.doc etc
2 min readOct 3, 2020
Instead of web pages, we can also load the document files into iOS WebView like .pdf, .txt, .doc etc.. loadData method is used to load NSData into webview.
Swift
//Assuming there is a text file in the project named "home.txt".let localFilePath = NSBundle.mainBundle().pathForResource(“home”, ofType:”txt”);
let data = NSFileManager.defaultManager().contentsAtPath(localFilePath!);
webview.loadData(data!, MIMEType: “application/txt”, textEncodingName:”UTF-8" , baseURL: NSURL())
Objective-C
//Assuming there is a text file in the project named "home.txt".NSString *localFilePath = [[NSBundle mainBundle] pathForResource:@”home” ofType:@”txt”];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:localFilePath];
[webview loadData:data MIMEType:@”application/txt” textEncodingName:@”UTF-8" baseURL:[NSURL new]];
Load local HTML file in webView
The following line of code loads the content of the HTML file into the webView
webView.loadRequest(NSURLRequest(URL: NSURL(fileURLWithPath:
NSBundle.mainBundle().pathForResource("YOUR HTML FILE", ofType: "html")!})
If your HTML file is called index.html replace YOUR HTML FILE with index.
You can use this code either in viewDidLoad() or viewDidAppear() or any other function
Make links That inside UIWebview clickable