ios - 访问并通知数据更改 firebase IOS
<p><p>我想通知在同一“房间”中的用户进行更改。场景:我有一个匿名设备,其 ID 和名称一起保存。我有一个具有唯一 ID 和名称的房间。我根据设备 ID 和房间 ID 建立了它们之间的链接。 </p>
<p>看起来像这样:</p>
<p> <a href="/image/hdp6N.png" rel="noreferrer noopener nofollow"><img src="/image/hdp6N.png" alt="enter image description here"/></a> </p>
<p>应通知在同一 key 下链接的设备室“表”中的每个设备。当该键下的数据发生变化时。但现在我没有得到的部分。</p>
<p>我想在设备房间键下获取每个设备的设备名称。是的,当名称更改时,我也想获得更新。我怎样才能通过授权等来做到这一点? </p>
<p>我现在有这个基本代码可以将所有这些数据写入数据库:</p>
<pre><code>var ref: DatabaseReference! = Database.database().reference()
ref.child("devices").child(user!.uid).child("device_name").setValue("iPhone test")
let newRef = ref.child("rooms").childByAutoId()
newRef.child("name").setValue("Room test")
ref.child("devicesrooms").child(newRef.key).child(user!.uid).setValue(true)
let ev = ref.child("devicesrooms").child(newRef.key)
ev.observeSingleEvent(of: .childAdded, with: { (DataSnapshot) in
print("changed")
})
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>如果您想知道名称何时更改,您需要使用 <strong>observe</strong> 而不是 <strong>observeSingleEvent</strong>。</p>
<p>我认为你需要这样的东西:</p>
<pre><code>var deviceNames = ()
var deviceHandles = ()
// Listen for added devices
ev.observe(.childAdded, with: { (snapshot) -> Void in
// Retrieve device key
let deviceKey = snapshot.key
// Add observer on device
var handle: UInt = 0
handle = ref.child("devices").child(deviceKey).observe(.value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let deviceName = value?["device_name"] as? String ?? ""
// Update or Add deviceName and handle in your dictionary
deviceNames = deviceName
deviceHandles = handle
})
})
// Listen for removed devices
ev.observe(.childRemoved, with: { (snapshot) -> Void in
let deviceKey = snapshot.key
// Remove deviceName from your dictionary
deviceNames = nil
// Retrieve handle from your dictionary
if let handle = deviceHandles {
// Remove observer on device
ref.child("devices").child(deviceKey).removeObserverWithHandle(handle)
}
// Remove handle from your dictionary
deviceHandles = nil
})
</code></pre>
<p>这里是 <a href="https://firebase.google.com/docs/database/ios/read-and-write" rel="noreferrer noopener nofollow">Firebase Realtime Database documentation</a> .</p></p>
<p style="font-size: 20px;">关于ios - 访问并通知数据更改 firebase IOS,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/45246882/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/45246882/
</a>
</p>
页:
[1]