Call Swift function from Bundle
Asked Answered
A

1

0

I have declared a function in a custom bundle using Xcode and Swift.

MyBundle.bundle —> File.swift —> func …() {}

How do I call that function from another project using Foundation.Bundle?

Avocation answered 28/5, 2020 at 19:7 Comment(2)
You can cast it to the actual type. See for example https://mcmap.net/q/50122/-how-to-create-an-instance-of-a-class-from-a-string-in-swift.Tallyman
@MartinR Unfortunately I cannot do this as I do not have access to the implementation in my code. I know the names of the functions only because I wrote them. ThanksAvocation
Y
1

Well you can't call it directly but probably you can make some way around that might work.

You can create an instance of that class from string using NSClassFromString and then you call the method using that call

Something like below

func getClassName(_ strClassName: String) -> AnyClass! {
   let bundle = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String;
    let requiredClass: AnyClass = NSClassFromString("\(namespace).\(strClassName)")!;
    return requiredClass;
}

Then you can call the method using your class instance returned by the above method like

yourClassInstance.perform(Selector("functionName"))
Youmans answered 28/5, 2020 at 21:1 Comment(1)
Conform the class to NSObject and declare it and the method with @objc(ClassOrMethodName). Cast the class loaded from bundle to NSObject.Type and then perform the selector as you said. Thanks!Avocation

© 2022 - 2024 — McMap. All rights reserved.