How to load HTML code or file in UIWebView using swift?

Let me tell you my one secret about iOS designing. Sometime, in our design, we have to use table views / grids for example bank statement. If you are familiar with iOS designing and auto layout, you already know how difficult it is to design complex tables or grids. In such situations, I use UIWebView. In background I prepare an html source code, then display the code in web view. Today I’ll tell you how to load source codes in web view using swift. After that, I’ll show how to load local html file in web view.
 1. Create an iOS application in Xcode.
2. Add a web view in the View controller of the storyboard

UIWebView3. Drag and drop web view’s IBOutlet to our ViewController.swift

4. Write a method to load string in UIWebView

In the above code, we created a constant (variable) htmlCode and wrote some html codes there. In the second line we loaded the htmlCode in our web view.

5. Call the method in ViewDidLoad:
Run the code and see what have you done.

Load local HTML file in UIWebView

Writing source codes in ViewController is painful and time wasting. Better approach is to create html file in Dreamweaver or Sublimetext or any other html editor. We’ll save that file in iOS project and load in web view. So, let’s begin our work.
  1. Create an iOS application in Xcode.
  2. Add a web view in the View controller of the storyboard
    screen-shot-2016-09-13-at-10-45-27-am
  3. Drag and drop web view’s IBOutlet to our ViewController.swift
  4. Create an html file using Sublime text or Dreamweaver or any other html editor. Save the file in a folder and open that folder.screen-shot-2016-09-20-at-10-06-44-pm
  5. Drag the file from folder to our Xcode’s Project Navigator. After you drag and drop, a dialog box will appear. In the dialog box check the “Copy items if needed” checkbox.
  6. Write a method to load local html in UIWebView
  7. Call loadHtmlFile() method in viewDidLoad method:

You can download the whole project from github

Leave a Reply