Search code examples
iosswiftcordova-plugins

How are parameters of various types accessed in Cordova iOS plugins written in Swift


The available documentation for cordova plugins in iOS is pretty poor, and assumes knowledge of Objective C (which I have never learned). It also seems to skip over certain things you're likely to need to know, like what a CDVInvokedUrlCommand is, exactly, and what types of values can be extracted from it.

I see from the header file for the type that it contains a method argumentAtIndex:, which I presume from Swift examples that I've seen interacts with the swift subscript operator, as these suggest command.arguments[number] as a means of getting the argument. However, I've seen no examples at any point that retrieve an argument of any type other than strings (which return either String or NSString ... and to be honest, I'm not really sure what the difference between these types is). So as I understand it, if I get string values, I can extract them like this:

@objc(myStringAction:)
func myStringAction (command: CDVInvokedUrlCommand) {
    let firstString = command.arguments[0] as String;
    let secondString = command.arguments[1] as String;
    ...
}

So, assuming I'm implementing another action myComplexAction which receives: an integer, a floating point number, an array of integers, and an object containing string values. How can I extract these into appropriate variables, and what are the resulting types?


Solution

  • After some research, a little bit of learning to read Objective C, and a whole load of digging in the badly-documented Cordova iOS platform library source code, it turns out that the arguments array in the CDVInvokedUrlCommand class is simply a standard array that is initialized from a JSON string using the standard platform NSJSONSerialization service. Therefore, you can assume that the array contains entries of one of the following types:

    • NSString, NSNumber, or NSNull for standard basic types.
    • Note that NSNumber is used to encode boolean values as well as numeric ones
    • NSArray with the same kind of entry types for any arrays
    • NSDictionary with NSString keys and the same kind of entry types for object values.

    Referencing from Swift, the following conversions to standard Swift value types are handled by the runtime:

    • NSString can be converted to String using as (or implicitly for Swift 2 or earlier)
    • NSNumber can be converted to an optional of any Swift numeric type using the as? operator (the conversion will fail if the contained number isn't representable in the target type).
    • NSNull doesn't get converted, but can be tested for using is
    • NSDictionary is implicitly convertible to [AnyHashable:Any]
    • NSArray is implicitly converted to [Any].