ionic capacitor从Swift调用TypeScript方法

huangapple go评论66阅读模式
英文:

ionic capacitor call typescript method from swift

问题

以下是翻译好的部分:

我有一个使用Ionic Capacitor的应用程序,其中包含一个自定义的本地插件。从TypeScript调用本地代码可以正常工作,我的Swift代码被调用并返回了Promise。但是,我还希望Swift代码能够调用一些TypeScript方法(主要是进行HTTP调用),但我不知道该如何实现。

根据我所了解的一些阅读:

let script = "window.MyService.typescriptMethod();";
self.bridge!.webView!.evaluateJavaScript(script, completionHandler: { (result, error) in
    if let error = error {
        print("Error calling TypeScript method: \(error.localizedDescription)")
    } else {
        if let resultString = result as? String {
            print(resultString)
        } else {
            print("Unexpected result from TypeScript method")
        }
    }
})

然而,它无法找到MyService,因为它未定义。MyService在Ionic的一侧已经定义,并且可以从那里调用。所以我不确定如何在Swift内部引用它,有人可以建议吗?

英文:

I have an ionic capacitor app which has a custom native plugin. Calling the native code from TypeScript works fine, my swift code is called and the promise is returned. However I would also like the swift code to be able to call a couple of TypeScript methods (mainly to do http calls) but can't figure out how to.

From some reading I've found:

let script = "window.MyService.typescriptMethod();";
            self.bridge!.webView!.evaluateJavaScript(script, completionHandler: { (result, error) in
                if let error = error {
                    print("Error calling TypeScript method: \(error.localizedDescription)")
                } else {
                    if let resultString = result as? String {
                        print(resultString)
                    } else {
                        print("Unexpected result from TypeScript method")
                    }
                }
            })

However it is unable to find MyService as it's undefined. MyService is defined on the ionic side and is callable from there. So I'm not sure how to reference it from within swift, can anyone suggest how?

答案1

得分: -1

要在Ionic Capacitor应用中从Swift调用TypeScript方法,您可以使用window对象来访问在Ionic应用的TypeScript代码中定义的全局JavaScript函数。

假设您在Ionic应用中定义了一个TypeScript函数typescriptMethod(),您可以像这样从Swift插件中调用它:

  • 首先,确保您的TypeScript函数可以从全局范围访问。您可以通过将该函数附加到TypeScript代码中的window对象来实现此目标:
// 在您的TypeScript代码中
window.MyService = {
    typescriptMethod: function() {
        console.log("TypeScript method called from Swift!");
        // 您可以在这里执行HTTP调用或其他逻辑
    }
};
  • 现在,在您的Swift代码中,您可以使用webView.evaluateJavaScript方法调用TypeScript方法:
// 在您的Swift代码中
let script = "window.MyService.typescriptMethod();"

self.bridge?.webView?.evaluateJavaScript(script, completionHandler: { (result, error) in
    if let error = error {
        print("Error calling TypeScript method: \(error.localizedDescription)")
    } else {
        if let resultString = result as? String {
            print(resultString)
        } else {
            print("Unexpected result from TypeScript method")
        }
    }
})

通过此设置,当您调用包含上述代码的Swift方法时,它将触发在您的TypeScript代码中定义的typescriptMethod(),允许您从Ionic应用执行HTTP调用或任何其他所需的逻辑。

只需确保在从Swift调用它之前,TypeScript方法(typescriptMethod())已经被定义并且可访问。该方法应该在一个位置声明,以确保在Swift插件尝试调用它时在全局范围内可用。

英文:

To call TypeScript methods from Swift in an Ionic Capacitor app, you can use the window object to access global JavaScript functions defined in your Ionic app's TypeScript code.

Assuming you have a TypeScript function typescriptMethod() defined in your Ionic app, you can call it from your Swift plugin like this:

  • First, make sure your TypeScript function is accessible from the global scope. You can achieve this by attaching the function to the window object in your TypeScript code:

    // In your TypeScript code
    window.MyService = {
        typescriptMethod: function() {
            console.log("TypeScript method called from Swift!");
            // You can put your http calls or other logic here
         }
    };
    
  • Now, in your Swift code, you can call the TypeScript method using the webView.evaluateJavaScript method:

     // In your Swift code
     let script = "window.MyService.typescriptMethod();"
    
     self.bridge?.webView?.evaluateJavaScript(script, completionHandler: { (result, error) in
     if let error = error {
         print("Error calling TypeScript method: \(error.localizedDescription)")
     } else {
     if let resultString = result as? String {
         print(resultString)
     } else {
         print("Unexpected result from TypeScript method")
       }
     }
     })
    

With this setup, when you call the Swift method that contains the above code, it will trigger the typescriptMethod() defined in your TypeScript code, allowing you to perform HTTP calls or any other logic you need from your Ionic app.

Just ensure that the TypeScript method (typescriptMethod()) is defined and accessible before you call it from Swift. The method should be declared in a place that ensures it is available in the global scope when your Swift plugin attempts to call it.

huangapple
  • 本文由 发表于 2023年7月23日 14:18:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76746859.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定