-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathXWebView.swift
More file actions
187 lines (169 loc) · 7.65 KB
/
XWebView.swift
File metadata and controls
187 lines (169 loc) · 7.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/*
Copyright 2015 XWebView
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import ObjectiveC
import WebKit
extension WKWebView {
public func loadPlugin(object: AnyObject, namespace: String) -> XWVScriptObject? {
let channel = XWVChannel(name: nil, webView: self)
return channel.bindPlugin(object, toNamespace: namespace)
}
func prepareForPlugin() {
let key = unsafeAddressOf(XWVChannel)
if objc_getAssociatedObject(self, key) != nil { return }
let bundle = NSBundle(forClass: XWVChannel.self)
guard let path = bundle.pathForResource("xwebview", ofType: "js"),
let source = try? NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) else {
preconditionFailure("FATAL: Internal error")
}
let time = WKUserScriptInjectionTime.AtDocumentStart
let script = WKUserScript(source: source as String, injectionTime: time, forMainFrameOnly: true)
let xwvplugin = XWVUserScript(webView: self, script: script, namespace: "XWVPlugin")
objc_setAssociatedObject(self, key, xwvplugin, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
extension WKWebView {
// Synchronized evaluateJavaScript
public func evaluateJavaScript(script: String, error: NSErrorPointer = nil) -> AnyObject? {
var result: AnyObject?
var done = false
let timeout = 3.0
if NSThread.isMainThread() {
evaluateJavaScript(script) {
(obj: AnyObject?, err: NSError?)->Void in
result = obj
if error != nil {
error.memory = err
}
done = true
}
while !done {
let reason = CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout, true)
if reason != CFRunLoopRunResult.HandledSource {
break
}
}
} else {
let condition: NSCondition = NSCondition()
dispatch_async(dispatch_get_main_queue()) {
[weak self] in
self?.evaluateJavaScript(script) {
(obj: AnyObject?, err: NSError?)->Void in
condition.lock()
result = obj
if error != nil {
error.memory = err
}
done = true
condition.signal()
condition.unlock()
}
}
condition.lock()
while !done {
if !condition.waitUntilDate(NSDate(timeIntervalSinceNow: timeout)) {
break
}
}
condition.unlock()
}
if !done {
print("<XWV> ERROR: Timeout to evaluate script.")
}
return result
}
}
extension WKWebView {
// WKWebView can't load file URL on iOS 8.x devices.
// We have to start an embedded http server for proxy.
// When running on iOS 8.x, we provide the same API as on iOS 9.
// On iOS 9 and above, we do nothing.
// Swift 2 doesn't support override +load method of NSObject, override +initialize instead.
// See http://nshipster.com/swift-objc-runtime/
private static var initialized: dispatch_once_t = 0
public override class func initialize() {
guard self == WKWebView.self else { return }
dispatch_once(&initialized) {
let loadFileURLSelector = Selector("loadFileURL:allowingReadAccessToURL:")
let loadHTMLStringSelector = Selector("loadHTMLString:baseURL:")
let customLoadHTMLStringSelector = Selector("_loadHTMLString:baseURL:")
let customLoadFileURLSelector = Selector("_loadFileURL:allowingReadAccessToURL:")
let loadFileURLMethod = class_getInstanceMethod(
self,
customLoadFileURLSelector
)
let loadHTMLStringMethod = class_getInstanceMethod(
self,
customLoadHTMLStringSelector
)
assert(loadFileURLMethod != nil && loadHTMLStringMethod != nil)
class_addMethod(
self,
loadFileURLSelector,
method_getImplementation(loadFileURLMethod),
method_getTypeEncoding(loadFileURLMethod)
)
method_exchangeImplementations(
class_getInstanceMethod(self, loadHTMLStringSelector),
class_getInstanceMethod(self, customLoadHTMLStringSelector)
)
}
}
@objc private func _loadFileURL(URL: NSURL, allowingReadAccessToURL readAccessURL: NSURL) -> WKNavigation? {
precondition(URL.fileURL && readAccessURL.fileURL)
let fileManager = NSFileManager.defaultManager()
var relationship: NSURLRelationship = NSURLRelationship.Other
_ = try? fileManager.getRelationship(&relationship, ofDirectoryAtURL: readAccessURL, toItemAtURL: URL)
var isDirectory: ObjCBool = false
if fileManager.fileExistsAtPath(readAccessURL.path!, isDirectory: &isDirectory) &&
isDirectory && relationship != NSURLRelationship.Other {
let port = startHttpd(documentRoot: readAccessURL.path!)
var path = URL.path![readAccessURL.path!.endIndex ..< URL.path!.endIndex]
if let query = URL.query { path += "?\(query)" }
if let fragment = URL.fragment { path += "#\(fragment)" }
let url = NSURL(string: path , relativeToURL: NSURL(string: "http://127.0.0.1:\(port)"))
return loadRequest(NSURLRequest(URL: url!));
}
return nil
}
// Although iOS 9.x loadHTMLString and loadData can't use baseURL with file protocol access.
// But for Simulator you can use loadHTMLString and loadData with file:/// as baseURL and access
// all of your resources. Accessing local data is restricted for devices and the unique folder
// that you can access is tmp folder.
//
// It continues to be necessary with you pretend to render pages such as dynamic templates.
@objc private func _loadHTMLString(html: String, baseURL: NSURL) -> WKNavigation? {
guard baseURL.fileURL else {
// call original method implementation
return _loadHTMLString(html, baseURL: baseURL)
}
let fileManager = NSFileManager.defaultManager()
var isDirectory: ObjCBool = false
if fileManager.fileExistsAtPath(baseURL.path!, isDirectory: &isDirectory) && isDirectory {
let port = startHttpd(documentRoot: baseURL.path!)
let url = NSURL(string: "http://127.0.0.1:\(port)/")
return loadHTMLString(html, baseURL: url)
}
return nil
}
private func startHttpd(documentRoot root: String) -> in_port_t {
let key = unsafeAddressOf(XWVHttpServer)
var httpd = objc_getAssociatedObject(self, key) as? XWVHttpServer
if httpd == nil {
httpd = XWVHttpServer(documentRoot: root)
httpd!.start()
objc_setAssociatedObject(self, key, httpd!, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return httpd!.port
}
}