你如何在swift中使用CDVPluginResult()来返回一个对象数组?

时间:2016-09-27 21:17:39

标签: javascript ios swift2 cordova-plugins

我正在按照这个方法使用swift创建一个cordova插件: http://moduscreate.com/writing-a-cordova-plugin-in-swift-for-ios/

我的版本似乎有用 - 我可以使用CDVPluginResult()将正确的数据返回给JS应用程序,但是我必须在ios中序列化数据,然后在JS中序列化JSON.parse

// swift
pluginResult = CDVPluginResult(
        status: CDVCommandStatus_OK,
        messageAsString: data.toJSON()
)
self.commandDelegate!.sendPluginResult(
  pluginResult,
  callbackId: command.callbackId
)

// JS
var successCallback = function (result) {
    try {
        var data = JSON.parse(result);
        callback(null, data);
    }
    catch (err) {
        callback(err, result);
    }
};
var errorCallback = function (err) { return callback(err, undefined); };
exec(successCallback, errorCallback, "myPlugin", "getData", [arg0]);

但是如何使用messageAsArraymessageAsArrayBuffermessageAsMultipart将我的数据作为JS返回object[]?似乎没什么用......

示例:

class MyObj: NSObject, NSCoding {
   let uuid: String

   // see: https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson10.html
   func encodeWithCoder(aCoder: NSCoder) {
       aCoder.encodeObject(self.uuid, forKey: "uuid")
   }

   required init?(coder aDecoder: NSCoder) {
       guard
           let uuid = aDecoder.decodeObjectForKey("uuid") as! String?
           else {
               return nil
       }
       self.uuid = uuid

       super.init()
   }

   required init(uuid: String) {
       self.uuid = uuid
       super.init()
   }
}

var data : [MyObj] = [...]
pluginResult = CDVPluginResult(
  status: CDVCommandStatus_OK,
  // messageAsString: toJSON(data)

  // How do I return swift [MyObject] as JS object[]?
  messageAsArray: data.map({o in NSKeyedArchiver.archivedDataWithRootObject(o))

)

1 个答案:

答案 0 :(得分:0)

使用messageAs参数返回

  • 来自类型的JSON对象删除了Swift词典:[AnyHashable : Any]

  • 来自Swift数组(字典)的JSON数组(对象):[[AnyHashable : Any]]

示例:

    let foo = ["foo": 123] as [AnyHashable : Any]
    let bar = ["bar": 234] as [AnyHashable : Any]
    let baz = ["baz": 456] as [AnyHashable : Any]
    let array = [foo, bar, baz]
    let pluginResult = CDVPluginResult(
        status: CDVCommandStatus_OK,
        messageAs: array
    )

返回浏览器回调中的对象[{foo:123}, {bar:234}, {baz:456}]