Wednesday, July 1, 2015

Display a web page with UIWebView and insert a JavaScript file using stringByEvaluatingJavaScriptFromString

This is a tutorial about inserting JavaScript code into the web page being read.

1. Select the storyboard and disable the Use Auto Layout and Use Size Classes option.


2. Drag a UIWebView to the storyboard.


3. Control-drag the UIWebView to ViewControl.swift

    @IBOutlet weak var myWebView: UIWebView!

4. Create an index.html file in the project:

<HTML>
    <HEAD>
        <TITLE>My Title</TITLE>
    </HEAD>
    <BODY>
        <H2><CENTER>Hello World</CENTER></H2>
    </BODY>
</HTML>

5. Create a JavaScript.js file in the project:


alert('JavaScript!');

6. Complete the ViewController.swift file as below:

import UIKit

class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var myWebView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        var myPath = NSBundle.mainBundle().pathForResource("index", ofType: "html")
        myWebView.delegate = self //For webViewDidFinishLoad to be called
        myWebView.loadRequest(NSURLRequest(URL: NSURL(string: myPath!)!))
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        let jsPath = NSBundle.mainBundle().pathForResource("JavaScript", ofType: "js")
        let jsContent = NSString(contentsOfFile: jsPath!, encoding: NSUTF8StringEncoding, error: nil) as! String
        
        myWebView.stringByEvaluatingJavaScriptFromString(jsContent)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

7. The alert window:

The HTML file is displayed in UIWebView:


1 comment: