2016-09-27 65 views
0

我下面這個HOWTO創建科爾多瓦插件使用SWIFT: http://moduscreate.com/writing-a-cordova-plugin-in-swift-for-ios/如何在swift中使用CDVPluginResult()來返回對象數組?

我的版本似乎工作 - 我可以使用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我的數據返回給JSobject[]?似乎沒有任何工作...

例如:

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)) 

) 

回答

0

使用messageAs參數返回

  • 從類型擦除斯威夫特字典

    JSON對象:[AnyHashable : Any]

  • JSON數組(對象)來自Swift數組(字典):[[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}]

相關問題