Call Swift function from Cordova

31 views
Skip to first unread message

Rajeev Piyare

unread,
Jun 13, 2017, 11:25:35 AM6/13/17
to phonegap

I have a native iOS app written in Swift and it works on standalone. However, currently, I am exploring Cordova and developing a plugin for it using the Swift codes that I already have. Let's say my native Swift code is the following and the function that I want to call is startDataLog():

func startDataLog() {
  // Set file logging parameters and do some logging etc...
  let fileName = "log_\(dateFormatter.string(from: Date())).log"
  let filePath = URL(fileURLWithPath: 
  (NSSearchPathForDirectoriesInDomains(.documentDirectory, 
  .userDomainMask, true)[0] as 
  NSString).appendingPathComponent(fileName))
  //do other stuffs here...
 }

Assuming that the plugin.xml and the bridging header are correctly configured for the new plugin: First, I need to add this in www/plugin.js that calls the iOS codes. In my case startDataLog:

var exec = require('cordova/exec');
var serviceName = 'DriverAppPlugin'

module.exports = {
  'startDataLog': function (successCallback, errorCallback) {
   cordova.exec(successCallback, errorCallback, serviceName, 
   'startDataLog', [])
    },
  }

Then in my native Swift code I will have to add the following:

@objc(CentralPlugin) class CentralPlugin: CDVPlugin {
 func startDataLog(command: CDVInvokedUrlCommand) {
   // Set file logging parameters and does some extras
   let fileName = "log_\(dateFormatter.string(from: Date())).log"
   let filePath = URL(fileURLWithPath: 
   (NSSearchPathForDirectoriesInDomains(.documentDirectory, 
   .userDomainMask, true)[0] as 
   NSString).appendingPathComponent(fileName))
   //do other stuffs here...
     }
   }     

What is unclear to me is if this is what needs to be done to the native Swift code or the function that I want to call? Is adding

(command: CDVInvokedUrlCommand)

to the func is correct or am I doing something terribly wrong here. I am new to Cordova and as a matter of fact, there are not many tutorials that are based on integrating Cordova + Swift.

Any feedback or directions will be really helpful to kickstart my plugin development. Please suggest.

Reply all
Reply to author
Forward
0 new messages