Implementing Native Functions
When JavaScript calls an enClose
function, The native side of the enClose framework searches for a matching selector implementation in the MainViewController
.
If found, the method executes on the native side, receiving any arguments passed via the data
, successCallback
, and errorCallback
parameters as a dictionary of type [String: String]
.
Implementation Requirements
- Implement native methods in the
MainViewController.swift
file - Tag methods with
@objc
attribute - Use the
evaluateJavascript
method to invoke JavaScript callbacks
When adding new native methods to your project, open the MainViewController.swift
file and locate the JavaScript Native Interface section identified by the comment block shown below.
Implement all your native methods immediately following this section to maintain consistent code organization throughout the project. This approach ensures that all JavaScript-accessible native methods remain logically grouped and easily discoverable within your codebase.
// MARK: JavaScript Native Interface
/*
This section bridges JavaScript calls to native Swift implementations.
Add your @objc exposed functions below this comment block to maintain code organization.
Keep interface methods simple and delegate complex logic to dedicated classes.
*/
Following this convention ensures that all JavaScript-accessible native methods remain organized and easily discoverable within your codebase.
Handling Callbacks
To provide success or error responses:
- Extract the JavaScript callback function name from the
params
dictionary - Use the
evaluateJavascript
method to invoke the function with your response
Example Implementation
@objc func helloWorld(_ params: [String: String]) {
var javaScript: String = ""
// Play a system sound (1016 is a tweet sound)
let systemSoundID: SystemSoundID = 1016
AudioServicesPlaySystemSound(systemSoundID)
// Process success callback
let successResponse = "You have successfully called a native function from JavaScript!"
if let successCallback = params["successCallback"] {
javaScript = "\(successCallback)('\(successResponse)');"
}
// Invoke JavaScript callback
evaluateJavascript(javaScript: javaScript)
}