I'm attempting to integrate native Swift code into my NativeScript application. Despite following the guidelines provided in the documentation, specifically adding a Swift source file to App_Resources/iOS/src/
and using publicly exposed classes directly in TypeScript code, I am encountering an error stating Cannot find name 'TestClass'
.
To reproduce this issue, follow these steps:
- Create a new NativeScript project with iOS support using the command
tns create my-app-name --template tns-template-blank-ts
Note: In my case, I initially generated the app using
vue init nativescript-vue/vue-cli-template testapp
, which seems to be causing problems.
- Add a
TestClass.swift
file toApp_Resources/iOS/src/
import Foundation
public class TestClass: NSObject {
@objc public func echo(param: String) -> String {
return param
}
}
- Instantiate the class in any TypeScript file using
let instance = new TestClass()
- Run the command
tns debug ios
- The compilation will fail with
Cannot find name 'TestClass'
I have attempted different approaches such as generating TypeScript typings using
TNS_TYPESCRIPT_DECLARATIONS_PATH="$(pwd)/typings" tns build ios
or declaring the class as any with declare let KeyCommander: any;
to rule out TypeScript-related issues. However, neither approach resolved the problem. The first method did not generate typings for my custom class, resulting in TypeScript compilation errors. The second method allowed TypeScript to compile but caused a runtime crash with JS ERROR ReferenceError: Can't find variable: TestClass
.
I have confirmed that the Swift file is being compiled by intentionally introducing syntax errors that halt the build process.
My NativeScript version is 6.4.0
.
What could be missing in this integration?
Update: Upon further investigation, I realized that creating the app using
vue init nativescript-vue/vue-cli-template testapp
leads to the failure mentioned above. Conversely, apps created using the standard tns cli do not encounter this issue, as noted in Tyler Blake's answer. The question now arises: What is causing this discrepancy?