0

I'm porting an android app and using firebase in android it is possible to save a format in this way. How can i do this on Swift? I read that i can store only this kind of data

  • NSString
  • NSNumber
  • NSDictionary
  • NSArray

How can I store the obj in atomic operation? It's correct to store every field of the user object in separate action?

Firebase on Android

mDatabaseReferences.child("users").child(user.getUuid()).setValue(user)

4

3 回答 3

3

我通常将对象存储为 firebase 上的字典。如果在我的应用程序中,我有一个 User 对象,并且它具有如下属性:

class User {
var username = ""
var email = ""
var userID = ""
var consecutiveDaysLoggedOn = Int()
}



let newUser = User()
   newUser.username = "LeviYoder"
   newUser.email = "LeviYoder@LeviYoder.com"
   newUser.userID = "L735F802847A-"
   newUser.consecutiveDaysLoggedOn = 1

我只是将这些属性存储为字典,然后将该字典写入我的 firebase 数据库:

let userInfoDictionary = ["username" : newUser.username
                           "email" : newUser.email
                           "userID" : newUser.userID
              "consecutiveDaysLoggedOn" : newUser.consecutiveDaysLoggedOn]

let ref = Database.database().reference.child("UserInfo").child("SpecificUserFolder")
//      ref.setValue(userInfoDictionary) { (error:Error?, ref:DatabaseReference) in

ref.setValue(userInfoDictionary, withCompletionBlock: { err, ref in
    if let error = err {
        print("userInfoDictionary was not saved: \(error.localizedDescription)")
    } else {
        print("userInfoDictionary saved successfully!")
    }
}

这能解决你的问题吗?

于 2019-04-18T19:17:02.310 回答
1

我附带了一个小扩展,用于在 FireStore 的可读字典中转换标准 SwiftObject:

extension Encodable {
    var toDictionnary: [String : Any]? {
        guard let data =  try? JSONEncoder().encode(self) else {
            return nil
        }
        return try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
    }
}

例如,在我的模型中:

struct Order: Encodable {
    let symbol: String
    let shares: Int
    let price: Float
    let userID: String
}

用这条线调用:

let dictionnary = order.toDictionnary

这是生成的字典类型

4 elements
  ▿ 0 : 2 elements
    - key : "symbol"
    - value : FP.PAR
  ▿ 1 : 2 elements
    - key : "shares"
    - value : 10
  ▿ 2 : 2 elements
    - key : "userID"
    - value : fake_id
  ▿ 3 : 2 elements
    - key : "price"
    - value : 100
于 2020-12-13T13:06:09.333 回答
-1

利用

self.ref.child("users").child(user.uid).setValue(["username": username])
于 2019-04-18T17:24:17.113 回答