|
@@ -12,14 +12,16 @@ func createJSContext() -> JSContext {
|
|
|
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) } }")
|
|
|
+ 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 method == "POST" {
|
|
|
+ if let data = data {
|
|
|
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
|
+ request.httpBody = data.data(using: .utf8)
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
if let headers = headers {
|
|
@@ -28,8 +30,7 @@ func createJSContext() -> JSContext {
|
|
|
|
|
|
AF.request(request).response { response in
|
|
|
if let data = response.data {
|
|
|
- let responseString = String(data: data, encoding: .utf8)
|
|
|
- callback?.call(withArguments: [responseString, nil])
|
|
|
+ callback?.call(withArguments: [String(data: data, encoding: .utf8), nil])
|
|
|
}
|
|
|
if let error = response.error {
|
|
|
callback?.call(withArguments: [nil, error.localizedDescription])
|
|
@@ -51,10 +52,15 @@ func createJSContext() -> JSContext {
|
|
|
let ctx = createJSContext()
|
|
|
|
|
|
|
|
|
-// 在 JavaScript 脚本中使用 Alamofire
|
|
|
let script = """
|
|
|
- AF.request("GET", "http://api.mywidgetsnow.com/health",, null, null, function(result) {
|
|
|
- console.log(result);
|
|
|
+ AF.request("http://api.mywidgetsnow.com/health", "GET", null, null, function(data, err) {
|
|
|
+ console.log(data);
|
|
|
+ console.log(err);
|
|
|
+ });
|
|
|
+
|
|
|
+ AF.request("httpdddd://api.mywidgetsnow.com/health", "GET", null, null, function(data, err) {
|
|
|
+ console.log(data);
|
|
|
+ console.log(err);
|
|
|
});
|
|
|
"""
|
|
|
|