In my application, I am trying to prevent the user from liking a post twice. my current code is:
@State private var isLiked = false
HStack {
Button(action: {if isLiked == false{
postData.addLike(id: post.id)
isLiked = true
} else{
postData.unLike(id: post.id)
isLiked = false
}}, label: {
Image(systemName: isLiked ? "heart.fill" : "heart")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 20)
.foregroundColor(isLiked ? .red : .gray)
Currently, when the like button is first pressed, it turns red and "addLike" is performed. However, if I close the app and reopen it, the button is no longer red. I would like the button to stay red, no matter how many times the app is closed/reopened, until the user presses it to unlike it.
I've read about using UserDefaults, but those get cleared when the app is uninstalled. I have my app linked to Google Firebase, so I was thinking that when the app is liked, add the users ID to a column called "likedBy"? Then when the app is opened, have the app scan for the users ID to see if that post was already liked by them. I have no clue how to implement this.
Sorry if this is a stupid question, I am making this app for fun and to learn.
EDIT I've been able to partly solve this thanks to the answer I've marked below. I've set up an array in my backend (postData):
self.ref.collection("Posts").document(id).updateData([
"likedBy": FieldValue.arrayUnion([self.uid])
self.ref.collection("Posts").document(id).updateData([
"likedBy": FieldValue.arrayRemove([self.uid])
This code sets the user's UID into the likedBy array. Now, I need to figure out how to read this data, and then see if the user's UID is equal to a UID found on the array.
My new question: SwiftUI Firebase - Reading Array Data to see if string is equal to an array string