Advanced Concepts
Adding ObjectiveC/Swift Code to an application
You can add Objective-C/Swift source files to App_Resources/iOS/src
. For Objective-C files, create a .modulemap
file. To add a CocoaPod, edit App_Resources/iOS/Podfile
:
bash
App_Resources/
├─ iOS/
│ ├─ src/
│ │ ├─ Shimmer.swift
│ │ ├─ Shimmer.h
│ │ ├─ Shimmer.m
│ │ └─ module.modulemap
│ └─ Podfile
└─ ... more
Adding Swift code
Define the swfit file in App_Resources/iOS/src
.
swift
// HelloSwift.swift
import UIKit
class HelloSwift: NSObject {
@objc public var stringToReturn: String = "Hello from Swift!"
@objc public func getString() -> String {
return stringToReturn;
}
}
Given the example above, your JavaScript or TypeScript code can reference the Swift code by using the full class name:
ts
const helloSwift = new HelloSwift()
helloSwift.stringToReturn = 'Custom hello from Swift!'
console.log(helloSwift.getString())
// prints: Custom hello from Swift!
Using @objc
@objc
allows exposing variables and functions to use them from JS/TS, note that in the example the variables and methods have this notation.
Using @objcMembers
A shortcut to the @objc
notation is to use the @objcMembers
notation at the class level to make the entire class accessible.
swift
// HelloSwift.swift
import UIKit
@objcMembers
class HelloSwift: NSObject {
public var stringToReturn: String = "Hello from Swift!"
public func getString() -> String {
return stringToReturn;
}
}
- Previous
- Adding Java/Kotlin Code