从mapView中的firebase下载地址

时间:2017-09-27 12:19:51

标签: swift firebase firebase-realtime-database mapkit mkmapview

尝试从firebase上传地址并将其发布到mapView上。但由于某种原因,地址不想卸载。 firebase示例中字符串拼写的地址 - 莫斯科,某某街道,房屋1 。可能是什么原因导致数据无法加载?

parse_str($token_response, $signed_request);

if (isset($signed_request['access_token'])) {
    return $signed_request['access_token'];
}

火力地堡:

var allAddresses: String = ""

addressRef = Database.database().reference(withPath: "Address")

addressRef.observe(.value, with: { (snapshot) in

        let value = snapshot.value as! NSDictionary

        self.allAddresses = value["address"] as? String ?? ""
    })
}

2 个答案:

答案 0 :(得分:0)

使用可选的展开功能并在某些行上设置断点,以查看代码无法执行的操作:

var allAddresses: String = ""

addressRef.observe(.value, with: { (snapshot) in

        if let value = snapshot.value as? [String:Any] {
            if let address = value["address"] as? String {
                self.allAddresses =  address
            } else {
                print("no address in value")
            }
        } else {
            print("no value from firebase")
        }
    })
}

你也应该在swift中使用swift类型,这是一个很好的做法。

答案 1 :(得分:0)

您正在将值观察者附加到/Address,这意味着您可以获得包含该位置所有数据的快照。由于有多个子地址,因此您的代码需要处理这些地址。

最简单的方法是收听.childAdded而不是.value

var allAddresses: String = ""

addressRef = Database.database().reference(withPath: "Address")

addressRef.observe(.childAdded, with: { (snapshot) in

    let value = snapshot.value as! NSDictionary

    self.allAddresses = value["address"] as? String ?? ""
})

现在,您的代码会被每个地址触发。

您还可以坚持观察.value,然后在快照中循环结果:

var allAddresses: String = ""

addressRef = Database.database().reference(withPath: "Address")

addressRef.observe(.value, with: { (snapshot) in
    for address in snapshot.children.allObjects as [FIRDataSnapshot] {
        let value = address.value as! NSDictionary

        self.allAddresses = value["address"] as? String ?? ""
    })
})