TheDeveloperBlog.com

Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

<< Back to SWIFT

Swift UIWebView: LoadHtmlString Example

UIWebView. HTML is everywhere. This page is in HTML. With a UIWebView we can render any HTML string (or remote web page) in our iOS program.
Add Web View. To begin please open the object library pane in Xcode. Drag a Web View to your iOS device screen. Put it in a nice position.
Add outlet. Now press control and drag the Web View to your ViewController.swift file. It helps to have side-by-side panes in Xcode with the Assistant.

Outlet: An outlet is a field in our Swift file. It is a way for our Swift code to reference a control from the Main.storyboard.

Add code. What good is a Swift tutorial without any Swift code? Here we add some code to our ViewController to load an HTML string in our UIWebView.String

PageHtml: This is a constant that contains some HTML text. It has a background of "aliceblue," my favorite color.

LoadHTMLString: This method is an instance method on our UIWebView. We call this on the field added in the "add outlet" step.

Func
Example UIWebView code: Swift // // ViewController.swift // ExampleTimeD // // ... // import UIKit class ViewController: UIViewController { @IBOutlet weak var simpleWeb: UIWebView! override func viewDidLoad() { super.viewDidLoad() // somexampleHTML let pageHtml = "<html><p style=background:aliceblue>" + "<b>Hello friend,</b> " + "how are you?</p></html>"; // Use loadHTMLString to display content. // ... Use nil for baseURL. simpleWeb.loadHTMLString(pageHtml, baseURL: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
Run simulator. Will our program run? Or it will it cause a fatal error and terminate our existence? Please press the right arrow to find out.

Result: The HTML string is rendered in the Web View. The HTML paragraph is only one line, so we only see a single line of aliceblue color.

Some thoughts. In early versions of the iPhone, web apps were emphasized as the future. And still, with WebKit, we can load web pages with ease on iOS.
A review. With UIWebView we can do important things like browse Wikipedia (or this website) in an iOS application. The Web View can handle back and forward navigation.
© TheDeveloperBlog.com
The Dev Codes