将数组发布到Swift中的firebase数据库
题
我需要将数据发布到firebase数据库中,(就数组而言)只能接受typesNSArray
。 然而,应用程序需要添加到数组中
Json将被张贴的数据
Object: someObjectKey[ ArrayOfItems[ Item: someItemNumber Item: someItemNumber Item: someItemNumber ] TimeStamp: 102047355 SomeOtherTimeStamp: null SomeInt: 1111 someOtherInt: 2222 SomeBoolean: false ] }
目标
我怎样才能把上面的数据推送到数据库中?
尝试途径
– 将一个SwiftArray
成一个NSArray
– 将一个NSMutableArray
成一个NSArray
码
public func postToFireBase(){ var Timestamp: String { return "\(NSDate().timeIntervalSince1970 * 1000)" } var someInt = 1111 var someOtherInt = 2222 let myArrayOfStuff = convertItemsToNSArray() let post: [String : Any] = ["timestamp": Timestamp, "someInt": someInt, "someOtherInt": someOtherInt, "items": ItemList] //Method Call References the FIRDatabase.database.reference.child... FirebaseDatabaseService.databaseReference.setValue(post) } private func convertItemsToNSArray() -> NSArray{ var thisArray: NSMutableArray = [] for item in items{ thisArray.add(["name": "Foo", "key": "Bar", "someCoolInt": 1234]) } return thisArray //This won't work because it's coming back as NSMutableArray anyway }
干杯
我不记得究竟是什么原因,但也面临类似的问题,在android和Ios.workaround是保存该数组首先将其转换为字典。
假设我有一些经度和纬度:
我首先创build一个类来包装拉特和长。 我有一个函数来获取包装所需数据的字典。
class HiddenLatlng { private var latitude: Double private var longitude: Double init(lat: Double, lng: Double) { self.latitude = lat self.longitude = lng } func toDictionery() -> [ String : Double ] { var dict = [ String : Double ]() dict["latitude"] = self.latitude dict["longitude"] = self.longitude return dict }
}
就在将数组保存到firebase之前,首先使用上面的类将此数组转换为字典。
var dict = [String: AnyObject]() // main dictionary saved to firebase var dictArray = [ String : [String: Double] ]() // temp dictionary for (index, element) in hide.vertices.enumerate(){ dictArray[String(index)] = HiddenLatlng(lat: element.latitude, lng: element.longitude).toDictionery() } dict["eventLatLngList"] = dictArray // add temp dictionary to main dictionary.
`
现在我们可以把它保存到firebase。
self.reference.child("yourKey").child(key).updateChildValues(dict) { (error: NSError?, reference: FIRDatabaseReference) in completion(error) // if some error handle it. }
我希望它可以节省一些时间和麻烦:)
您的Firebase结构应该如下所示
-Yk8hsinuoioas90kp TimeStamp: 102047355 SomeOtherTimeStamp: null SomeInt: 1111 someOtherInt: 2222 SomeBoolean: false Items -Y9jkoma9kmmsd itemName: "The best item" itemPrice: "1.90" -Ymnk0s0s0k98s itemName: "Another great item" itemPrice: "9.99" -JYOjsomojkspy itemName: "The best item evah" itemPrice: "4.99"
为了得到这个,你只需要创build一个字典,并用childByAutoId创build父节点。 然后将子节点添加为键:值对,其中子节点也是“键:值”对的字典。
最后用a写一个字典
let thisThingRef = ref.childByAutoId() thisThingRef.setValue(myDict)
我可以编写一些代码来创build该字典,如果你需要它。
哦…你可能想要对数据进行非规范化处理,并将项目存储在一个单独的节点中,并保留对它的引用
-Yk8hsinuoioas90kp TimeStamp: 102047355 SomeOtherTimeStamp: null SomeInt: 1111 someOtherInt: 2222 SomeBoolean: false Items -Y9jkoma9kmmsd: true -Ymnk0s0s0k98s: true -JYOjsomojkspy: true