Skip to content

Instantly share code, notes, and snippets.

@revblaze
Last active May 25, 2020 18:13
Show Gist options
  • Save revblaze/9c8ba06b14cb3e70250d6b8158d0ea46 to your computer and use it in GitHub Desktop.
Save revblaze/9c8ba06b14cb3e70250d6b8158d0ea46 to your computer and use it in GitHub Desktop.
WebKit Extensions: Quick, easy and useful
import WebKit
extension WKWebView {
/// Quick and short load URL String in a WKWebView
func load(_ string: String) {
if let url = URL(string: string) {
let request = URLRequest(url: url)
load(request)
}
}
/// Quick and short load URL in a WKWebView
func load(_ url: URL) {
let request = URLRequest(url: url)
load(request)
}
/// Quick load a `file` (without `.html`) and `path` to the directory
/// # Usage
/// webView.loadFile("index", path: "Website")
/// - parameters:
/// - name: Name of the HTML file to load (without `.html`, ie. `"index"`)
/// - path: Path where the HTML file is located (`"website"` for `website/index.html`)
func loadFile(_ name: String, path: String) {
if let url = Bundle.main.url(forResource: name, withExtension: "html", subdirectory: path) {
self.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
load(request)
}
}
/// Evaluate JavaScript with escaping completion handler
func evaluate(script: String, completion: @escaping (Any?, Error?) -> Void) {
var finished = false
evaluateJavaScript(script, completionHandler: { (result, error) in
if error == nil {
if result != nil {
completion(result, nil)
}
} else {
completion(nil, error)
}
finished = true
})
while !finished {
RunLoop.current.run(mode: RunLoop.Mode(rawValue: "NSDefaultRunLoopMode"), before: NSDate.distantFuture)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment