12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- import JavaScriptCore
- import Alamofire
- func createJSContext() -> JSContext {
- let ctx = JSContext()
-
- // 注入 console.log
- ctx?.evaluateScript("var console = { log: function(message) { _consoleLog(message) } }")
- let consoleLog: @convention(block) (String) -> Void = { message in
- print("JavaScript Console.log: " + message)
- }
- ctx?.setObject(unsafeBitCast(consoleLog, to: AnyObject.self), forKeyedSubscript: "_consoleLog" as (NSCopying & NSObjectProtocol)?)
-
- // 注入AF
- ctx?.evaluateScript("var af = { request: function(url, method, data, headers, callback) { _request(url, method, data, headers, callback) } }")
- let af: @convention(block) (String, String, String?, [String: String]?, JSValue?) -> Void = { url, method, data, headers, callback in
- var request = URLRequest(url: URL(string: url)!)
- request.httpMethod = method
-
- if let data = data {
- request.setValue("application/json", forHTTPHeaderField: "Content-Type")
- request.httpBody = data.data(using: .utf8)
- }
-
- if let headers = headers {
- request.headers = HTTPHeaders(headers)
- }
-
- AF.request(request).response { response in
- if let data = response.data {
- let responseString = String(data: data, encoding: .utf8)
- callback?.call(withArguments: [responseString, nil])
- }
- if let error = response.error {
- callback?.call(withArguments: [nil, error.localizedDescription])
- }
- }
- }
- ctx?.setObject(unsafeBitCast(af, to: AnyObject.self), forKeyedSubscript: "_request" as (NSCopying & NSObjectProtocol)?)
-
- // 捕捉JS运行异常
- ctx?.exceptionHandler = { context, exception in
- if let exception = exception {
- print("JavaScript Exception: \(exception)")
- }
- }
-
- return ctx!
- }
- let ctx = createJSContext()
- // 在 JavaScript 脚本中使用 Alamofire
- let script = """
- AF.request("GET", "http://api.mywidgetsnow.com/health",, null, null, function(result) {
- console.log(result);
- });
- """
- // 执行 JavaScript 脚本
- ctx.evaluateScript(script)
- RunLoop.main.run()
|