[英]How can I send information from one user to another using Firebase realtime database?
我正在構建一個用戶可以交換位置的應用程序。
到目前為止,我已經構建了一個函數,用戶可以使用該函數發送他的位置並且任何其他用戶都可以看到它。 我想修改我的 sendLocation() 函數,以便將位置發送給特定用戶,並且只有該用戶才能看到它,但我不確定這樣做的最佳方法是什么。
這將用戶位置發送到數據庫
sendLocation = () => {
console.warn("sending location log", this.props);
firebase
.database()
.ref("/locations")
.child(this.currentUser.uid)
.child(Date.now())
.set({
uid: this.currentUser.uid,
user: user,
latitude: this.props.location.coords.latitude,
longitude: this.props.location.coords.longitude,
created_at: Date.now(),
order: -Date.now()
});
this.sendPushNotification();
};
這是我檢索位置的地方
readLocations = () => {
allLocations = [];
let locations = firebase
.database()
.ref("/locations")
.child(this.currentUser.uid)
.orderByChild("created_at")
.startAt(last12hours);
locations.on("value", snapshot => {
snapshot.forEach(thing => {
oneLocation = [];
oneLocation.push(
thing.val().uid,
thing.val().latitude,
thing.val().longitude,
thing.val().user
);
allLocations.push(oneLocation);
});
this.setState({ locations: allLocations }, () => {
});
});
};
我也可以訪問用戶信息。 在我將位置發送給用戶之前,將觸發此功能。
readFriends = () => {
allFriends = [];
let myFriends = firebase
.database()
.ref("/users")
.orderByChild("first_name");
myFriends.on("value", snapshot => {
snapshot.forEach(thing => {
oneFriend = [];
oneFriend.push(thing.val().first_name, thing.val().last_name);
allFriends.push(oneFriend);
});
this.setState({ friends: allFriends, modalVisible: true }, () => {
});
});
};
為了能夠檢測是否有人將他們的位置寫給朋友,您首先需要在數據庫中建立友誼模型。 一個非常簡單的模型是:
friends: {
uid1: {
uid2: true,
uid3: true
},
uid2: {
uid1: true
}
}
所以在上面的數據結構, uid1
標志着uid2
和uid3
當作自己的朋友,而uid2
也投桃報李,標志着uid1
作為他們的朋友。 您通常會保護上述內容,以便用戶只能使用以下內容寫他們自己的朋友:
{
"rules": {
"friends": {
"$uid": {
".write": "auth.uid === $uid"
}
}
}
}
現在,我們可以允許用戶為將他們標記為朋友的人寫下他們的位置。 我們將為此使用另一種數據結構,例如:
locations: {
uid1: {
uid2: "location of uid2"
}
}
因此,在上述情況下,用戶uid2
寫了自己的位置,以uid1/uid2
喜歡的東西:
firebase.database()
.ref("/locations")
.child("uid1") // the UID of someone who marked us as a friend
.child(this.currentUser.uid)
.set(...)
您可以通過以下方式保護上述寫入操作:
{
"rules": {
"locations": {
"$friendid": {
"$uid": {
".write": "auth.uid === $uid &&
root.child('friends').child($friendid).child(auth.uid).exists()"
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.