写入DB失败了吗?

时间:2017-03-29 16:36:10

标签: ios swift firebase firebase-realtime-database

我试图将2个数据写入db。

  @IBAction func show(button: UIButton) {

        let userRef = self.dataBaseRef.child("users/\(FIRAuth.auth()!.currentUser!.uid)")
        userRef.observe(.value, with: { (snapshot) in
            let user = User(snapshot: snapshot)
            let currentUser = user.email
            let request = Requests(requestBy: user.email!,
                                   requestTo: self.email!)

            let contactRef = self.ref.child(currentUser! + "--" + self.email!)
            contactRef.setValue(request.toAnyObject())
            self.items.append(request)
            print(request)
        }) { (error ) in
            print(error.localizedDescription)
        }

        self.dismiss(animated: true, completion: nil);

}

项目是一个数组

var items: [Requests] = []

user.email和self.email!我打印出来并不是空的。

请求文件外观

struct Requests {

let key: String
let requestBy: String
let requestTo: String
let ref: FIRDatabaseReference?

init(requestBy: String, requestTo: String, key: String = "") {
    self.key = key
    self.requestBy = requestBy
    self.requestTo = requestTo
    self.ref = nil
}

init(snapshot: FIRDataSnapshot) {
    key = snapshot.key
    let snapshotValue = snapshot.value as! [String: AnyObject]
    requestBy = snapshotValue["requestBy"] as! String
    requestTo = snapshotValue["requestTo"] as! String
    ref = snapshot.ref
}

func toAnyObject() -> Any {
    return [
        "requestBy": requestBy,
        "requestTo": requestTo
    ]
}

}

我收到错误 - 在展开“可选”值时意外地发现nil

2 个答案:

答案 0 :(得分:2)

根据我在您发布的代码中看到的内容,您创建了一个请求,但从未为ref属性赋值。但是,目前尚不清楚,因为我们无法看到它崩溃的位置或何时真正使用过。

另外,假设self.ref是可选的(因为你在可见代码中以这种方式处理过),那么这可能是问题所在:

让contactRef = self.ref.child

首先应检查是否可以打开该选项,例如:

if let realRef = self.ref { realRef.child(currentUser! + "--" + self.email!) }

答案 1 :(得分:0)

let currentUser = user.email  //this is not an optional
let request = Requests(requestBy: user.email!,
                                   requestTo: self.email!)

contactRef = self.ref.child(currentUser! + "--" + self.email!)

currentUser!不需要打开包装。