Ben 11 months ago
parent
commit
9365104861
2 changed files with 71 additions and 2 deletions
  1. 7 2
      js/info.js
  2. 64 0
      js/main.swift

+ 7 - 2
js/info.js

@@ -62,8 +62,13 @@ request = async (method, url, data = null, headers = {}, local) => {
             "body": data,
         }).then(res => res.text())
     }
-    return AF.request(method, url, data, headers)
-        .then(res => res.text());
+    return new Promise((resolve, reject) => {
+        const res = AF.request(method, url, data, headers);
+        if (res["error"]) {
+            reject(res["error"]);
+        }
+        return resolve(res["data"]);
+    })
 }
 
 getStringBetween = (string, needleStart, needleEnd, offsetStart = 0, offsetEnd = 0) => {

+ 64 - 0
js/main.swift

@@ -0,0 +1,64 @@
+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()