-
Notifications
You must be signed in to change notification settings - Fork 84
Quick Start
We start from the simplest HelloWorld example step by step to demonstrate the essential features of XWebView.
- Create a project
Create an iOS application project called HelloWorld with the "Single View Application" template in a working directory, and use language "Swift" for convenience.
- Use CocoaPods to install XWebView
Close the project you just created. In the root directory of the project, create a file named Podfile with the following contents:
platform :ios, '9.0'
use_frameworks!
target "HelloWorld" do
# XWebView 0.12.0 required for Swift 3.0.2. See https://github.com/xwv/XWebView if targeting versions of Swift below this.
pod 'XWebView', '~> 0.12.0'
end
Then run pod install in terminal to setup a workspace for you. When finished, open the HelloWorld.xcworkspace created by CocoaPods.
- Modify the ViewController
In the ViewController.swift file, find the viewDidLoad() method and add few lines:
// Do any additional setup after loading the view, typically from a nib.
let webview = WKWebView(frame: view.frame, configuration: WKWebViewConfiguration())
view.addSubview(webview)
webview.loadPlugin(HelloWorld(), namespace: "HelloWorld")
let root = Bundle.main.resourceURL!
let url = root.appendingPathComponent("index.html")
webview.loadFileURL(url, allowingReadAccessTo: root)Don't forget to import WebKit and XWebView frameworks.
- Write a plugin
In HelloWorld group, create a Swift source file named HelloWorld.swift. It's a fairly simple class.
import Foundation
import UIKit
class HelloWorld : NSObject {
// Add an underscore before parameter name (ie. make it anonymous) to prevent method name changing to showWithText when added to JavaScript environment.
func show(_ text: AnyObject?) {
let title = text as? String
DispatchQueue.main.async {
let alert = UIAlertView(title: title, message: nil, delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}
}- Lastly, the HTML.
Create an HTML file named index.html also in the HelloWorld group. The content is straightforward.
<html>
<head>
<meta name='viewport' content='width=device-width' />
</head>
<body>
<br />
<input type='button' value='Hello' onclick='window.HelloWorld.show("Hello, world!");' />
</body>
</html>It's worth to highlight here that there is no JavaScript wrapper for accessing the plugin object.
- Build and test
Build and run the application.
