main.swift 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import JavaScriptCore
  2. import Alamofire
  3. func createJSContext() -> JSContext {
  4. let ctx = JSContext()
  5. // 注入 console.log
  6. ctx?.evaluateScript("var console = { log: function(message) { _consoleLog(message) } }")
  7. let consoleLog: @convention(block) (String) -> Void = { message in
  8. print("JavaScript Console.log: " + message)
  9. }
  10. ctx?.setObject(unsafeBitCast(consoleLog, to: AnyObject.self), forKeyedSubscript: "_consoleLog" as (NSCopying & NSObjectProtocol)?)
  11. // 注入AF
  12. ctx?.evaluateScript("var af = { request: function(url, method, data, headers, callback) { _request(url, method, data, headers, callback) } }")
  13. let af: @convention(block) (String, String, String?, [String: String]?, JSValue?) -> Void = { url, method, data, headers, callback in
  14. var request = URLRequest(url: URL(string: url)!)
  15. request.httpMethod = method
  16. if let data = data {
  17. request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  18. request.httpBody = data.data(using: .utf8)
  19. }
  20. if let headers = headers {
  21. request.headers = HTTPHeaders(headers)
  22. }
  23. AF.request(request).response { response in
  24. if let data = response.data {
  25. let responseString = String(data: data, encoding: .utf8)
  26. callback?.call(withArguments: [responseString, nil])
  27. }
  28. if let error = response.error {
  29. callback?.call(withArguments: [nil, error.localizedDescription])
  30. }
  31. }
  32. }
  33. ctx?.setObject(unsafeBitCast(af, to: AnyObject.self), forKeyedSubscript: "_request" as (NSCopying & NSObjectProtocol)?)
  34. // 捕捉JS运行异常
  35. ctx?.exceptionHandler = { context, exception in
  36. if let exception = exception {
  37. print("JavaScript Exception: \(exception)")
  38. }
  39. }
  40. return ctx!
  41. }
  42. let ctx = createJSContext()
  43. // 在 JavaScript 脚本中使用 Alamofire
  44. let script = """
  45. AF.request("GET", "http://api.mywidgetsnow.com/health",, null, null, function(result) {
  46. console.log(result);
  47. });
  48. """
  49. // 执行 JavaScript 脚本
  50. ctx.evaluateScript(script)
  51. RunLoop.main.run()