I have a bit of a lengthy question, So I apologize in advance I will try to illustrate this to the best of my abilities. I am trying to establish a notifications view controller that calls different types of data from Firebase and sets different notification types.
In the image above, this is how the cells should look when a user sends a notification to firebase. The user associated with that specific notification type as called and posted onto the screen.
In the firebase structure, We see that all of the information Stored is saved under the UID of the user in the first picture and is set under that specific users notification to show who is sending them a notification which is correct. These users names and images show perfectly as well as the image on the right.
The code I use to save this information is below,
fileprivate func saveSwipeToDataBase(didLike: Any) {
let swipeDate = Int(NSDate().timeIntervalSince1970)
guard let uid = Auth.auth().currentUser?.uid else { return }
guard let cardUID = topCardView?.cardViewModel.uid else { return }
let documentData = ["workerId": uid,
"didLike": didLike,
"checked": 0,
"Swipe Date": swipeDate,
"type": SWIPE_INT_VALUE,
"posterId" : cardUID] as [String : Any]
self.postJobNotificationsIntoDatabseWithUID(uid: cardUID, values: documentData as [String : AnyObject])
}
private func postJobNotificationsIntoDatabseWithUID(uid: String, values: [String: AnyObject]) {
let ref = Database.database().reference(fromURL: "https://oddjobs-b131f.firebaseio.com/")
let usersReference = ref.child("notifications").child(uid).childByAutoId()
usersReference.setValue(values, withCompletionBlock: { (err, ref) in
if err != nil {
print("error saving data into firebase")
return
}
})
}
And below is how I retrieve this information and store it onto the Notifications View controller.
func fetchNotifications() {
guard let currentUID = Auth.auth().currentUser?.uid else { return }
NOTIFICATIONS_REF.child(currentUID).observeSingleEvent(of: .value) { (snapshot) in
guard let dictionary = snapshot.value as? Dictionary<String, AnyObject> else { return }
print(dictionary)
for (_, postingRawData) in dictionary {
guard let postingDictionary = postingRawData as? Dictionary<String, AnyObject> else { continue }
guard let uid = postingDictionary["workerId"] as? String else { continue }
Database.fetchUser(with: uid, completion: { (user) in
if let postId = postingDictionary["posterId"] as? String {
Database.fetchPoster(with: postId, completion: {(poster) in
let notification = userNotifications(user: user, poster: poster, dictionary: postingDictionary)
self.notifications.append(notification)
self.handleSortNotification()
})
} else {
let notification = userNotifications(user: user, dictionary: postingDictionary)
self.notifications.append(notification)
self.handleSortNotification()
}
})
}
}
}
Now that I got the correct way to setup up and show out of the way, I will show my enum and how I am distinguishing the different types of calls from firebase.
class userNotifications {
// MARK: - establish notificationTypes
enum NotificationType: Int, Printable {
case swipe
case accepted
case confirmed
case completed
case pay
var description: String {
switch self {
case .swipe: return " swiped on your Job "
case .accepted: return " accepted you to complete the job, "
case .confirmed: return " confirmed the job"
case .completed: return " completed the job"
case .pay: return " pay for completed"
}
}
init(index: Int) {
switch index {
case 0: self = .swipe
case 1: self = .accepted
case 2: self = .confirmed
case 3: self = .completed
case 4: self = .pay
default: self = .swipe
}
}
}
// MARK: - access firebaseData
var creationDate: Date!
var timeDate: Date!
var uid: String!
var fromId: String?
var workerId: String?
var user: User!
var poster: Poster!
var type: Int?
var notificationType: NotificationType!
var didCheck = false
init(user: User? = nil, poster: Poster? = nil, dictionary: Dictionary<String, AnyObject>) {
self.user = user
if let poster = poster {
self.poster = poster
}
if let swipeDate = dictionary["Swipe Date"] as? Double {
self.creationDate = Date(timeIntervalSince1970: swipeDate)
}
if let createDate = dictionary["creationDate"] as? Double {
self.creationDate = Date(timeIntervalSince1970: createDate)
}
if let swipeDate = dictionary["time&date"] as? Double {
self.timeDate = Date(timeIntervalSince1970: swipeDate)
}
if let type = dictionary["type"] as? Int {
self.notificationType = NotificationType(index: type)
}
if let uid = dictionary["uid"] as? String {
self.uid = uid
}
if let fromId = dictionary["fromId"] as? String {
self.fromId = fromId
}
if let workerId = dictionary["workerUID"] as? String {
self.workerId = workerId
}
if let checked = dictionary["checked"] as? Int {
if checked == 0 {
self.didCheck = false
} else {
self.didCheck = true
}
}
}
}
Above is the different types of notifications to be set.
Now, My issue is If I call a different notification type, such as .accepted, the information calls in a very different way.
The image above seems correct, However, the name and image are incorrect. it should be from the user ZacheryWilcox instead of Cjbwjdhbe. the user Cjbwjdhbe is the current user and the user who should be receing a notification from Zacherywilcox. not from itself.
In firebase, the information is saved as
the code I use to save this information is below
var workerUser: User? {
didSet {
let name = workerUser?.name
workerNameLabel.text = name
let workersUID = workerUser?.uid
workerNameLabel.text = name
guard let profileImage = workerUser?.profileImageUrl else { return }
workerImageView.loadImageUsingCacheWithUrlString(profileImage)
}
}
func saveUserData() {
let workUser = self.workerUser
guard let uid = Auth.auth().currentUser?.uid else { return }
let workerId = workUser?.uid
Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String : Any] else { return }
let user = User(dictionary: dictionary as [String : AnyObject])
workUser?.uid = snapshot.key
self.datePicker.datePickerMode = UIDatePicker.Mode.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd yyyy/ hh:mm a"
let selectedDate = dateFormatter.string(from: self.datePicker.date)
let creationDate = Int(NSDate().timeIntervalSince1970)
print(selectedDate)
let docData: [String: Any] = [
"workerId": workerId!,
"time&date": selectedDate,
"posterId" : uid,
"creationDate": creationDate,
"location": user.address!,
"type": 1,
"jobPost": "someUIDString",
"checked": 0,
]
self.postJobNotificationsIntoDatabseWithUID(uid: workerId!, values: docData as [String : AnyObject])
}, withCancel: { (err) in
print("attempting to load information")
})
print("Finished saving user info")
self.dismiss(animated: true, completion: {
print("Dismissal complete")
})
}
private func postJobNotificationsIntoDatabseWithUID(uid: String, values: [String: AnyObject]) {
let ref = Database.database().reference(fromURL: "https://oddjobs-b131f.firebaseio.com/")
let usersReference = ref.child("notifications").child(uid).childByAutoId()
usersReference.setValue(values, withCompletionBlock: { (err, ref) in
if err != nil {
print("error saving data into firebase")
return
}
})
}
When the type .accepted is being used to differentiate what notificationType is being called, the user who sent the notification is not being set correctly and I have no idea what is the reasoning behind this. The correct user that is sending this information over is Zacherywilcox, and that users image and name should be set to the user's notification screen. not the user Cjbe... I was wondering if anyone could help me fix these issues. Thank you in advance. I'm starting to think that the way I am saving the users information when accepting the user is incorrect.
When I am fetchingNotifications(), is it possible that since calling
guard let uid = postingDictionary["workerId"] as? String else { continue }
Database.fetchUser(with: uid, completion: { (user) in
if let postId = postingDictionary["posterId"] as? String {
has an effect on whats going on? if so, Is there a way to differentiate between what notificationType is being called and fetch what notifications has been called with their respective users?
Just update your code to:
func fetchNotifications() {
guard let currentUID = Auth.auth().currentUser?.uid else { return }
NOTIFICATIONS_REF.child(currentUID).observeSingleEvent(of: .value) { (snapshot) in
guard let dictionary = snapshot.value as? Dictionary<String, AnyObject> else { return }
print(dictionary)
let notificationId = snapshot.key
for (_, postingRawData) in dictionary {
guard let postingDictionary = postingRawData as? Dictionary<String, AnyObject> else { continue }
guard let type = postingDictionary["type"] as? Int else { continue }
guard let uid = (type == userNotifications.NotificationType.accepted.rawValue) ? postingDictionary["fromId"] as? String : postingDictionary["workerId"] as? String else { continue }
Database.fetchUser(with: uid, completion: { (user) in
if let postId = postingDictionary["fromId"] as? String {
Database.fetchPoster(with: postId, completion: {(poster) in
let notification = userNotifications(user: user, poster: poster, dictionary: postingDictionary)
self.notifications.append(notification)
self.handleSortNotification()
})
} else {
let notification = userNotifications(user: user, dictionary: postingDictionary)
self.notifications.append(notification)
self.handleSortNotification()
}
// NOTIFICATIONS_REF.child(currentUID).child(notificationId).child("checked").setValue(1)
})
}
}
}
This will solve your problem.
Related
In my page named service, xcode points to the user and gives an error. but it doesn't work. What do you think should I change?
my user is already optional. I think it is an index problem but I don't know how to solve it I would appreciate it if you could help.where do you think the problem
message.swift
import Firebase
struct Message {
let text: String
let toId: String
let fromId: String
var timestamp: Timestamp!
var user: User?
let isFromCurrentUser :Bool
init(dictionary: [String: Any]) {
self.text = dictionary["text"] as? String ?? ""
self.toId = dictionary["toId"] as? String ?? ""
self.fromId = dictionary["fromId"] as? String ?? ""
self.timestamp = dictionary["timestamp"] as? Timestamp ?? Timestamp(date: Date())
self.isFromCurrentUser = fromId == Auth.auth().currentUser?.uid
}
}
struct Conversation {
let user: User
let message : Message
}
Service.Swift
import Firebase
struct Service {
static func fetchUsers (completion: #escaping([User]) -> Void) {
var users = [User] ()
COLLECTION_USERS.getDocuments { (snapshot, error) in
snapshot?.documents.forEach({ (document) in
let dictionary = document.data()
let user = User(dictionary: dictionary)
users.append(user)
completion(users)
})
}
}
static func fetchUser(widhtUid uid: String, completion:#escaping([User]) ->Void) {
COLLECTION_USERS.document(uid).getDocument { (snapshot, error) in
guard let dictionary = snapshot?.data() else {return}
let user = User(dictionary: dictionary)
completion(user)
}
}
static func fetchConversations (completion: #escaping([Conversation]) ->Void) {
var conversations = [Conversation]()
guard let uid = Auth.auth().currentUser?.uid else {return}
let query = COLLECTION_MESSAGES.document(uid).collection("recent-messages").order(by: "timestamp")
query.addSnapshotListener { (snapshot, error) in
snapshot?.documentChanges.forEach({ change in
let dictionary = change.document.data()
let message = Message(dictionary: dictionary)
self.fetchUser(widhtUid: message.toId) { user in
let conversation = Conversation(user:user, message: message)
conversations.append(conversation)
completion(conversations)
}
})
}
}
static func fetchMessages (forUser user: User, completion: #escaping([Message])-> Void) {
var messages = [Message]()
guard let currentUid = Auth.auth().currentUser?.uid else {return}
let query = COLLECTION_MESSAGES.document(currentUid).collection(user.uid).order(by: "timestamp")
query.addSnapshotListener{(snapshot,error) in
snapshot?.documentChanges.forEach({ change in
if change.type == .added {
let dictionary = change.document.data ()
messages.append(Message(dictionary: dictionary))
completion(messages)
}
})
}
}
static func uploadMessage(message: String, to user: User, completion: ((Error?)->Void)?) {
guard let currentUid = Auth.auth().currentUser?.uid else {return}
let data = ["text": message,
"fromId": currentUid,
"toId": user.uid,
"timestamp" : Timestamp(date: Date())] as [String : Any]
COLLECTION_MESSAGES.document(currentUid).collection(user.uid).addDocument(data:data) { _ in
COLLECTION_MESSAGES.document(user.uid).collection(currentUid).addDocument(data:data,completion:completion)
COLLECTION_MESSAGES.document(currentUid).collection("recent- messages").document(user.uid).setData(data)
COLLECTION_MESSAGES.document(user.uid).collection("recent- messages").document(currentUid).setData(data)
}
}
}
In this method:
static func fetchUser(widhtUid uid: String, completion:#escaping ([User]) -> Void)
The completion closure's parameter should be a User, not an array of users - [User].
Xcode should point you to the line where this error happens...
Anyway, here
static func fetchUser(widhtUid uid: String, completion:#escaping([User]) ->Void) {
COLLECTION_USERS.document(uid).getDocument { (snapshot, error) in
guard let dictionary = snapshot?.data() else {return}
let user = User(dictionary: dictionary)
completion(user)
}
}
Your completion:#escaping([User]) ->Void) expects an array [User] , but you invoke it with just one User object here completion(user)
i am having an issue i can get the value from my realtime database. i'm using this function. bu maybe i'm doing something wrong
enter c func getPlays(handler: #escaping(_ boat: [GameToSend]) -> ()) {
PLAYS.observeSingleEvent(of: .value) { (playSnap) in
var plays = [GameToSend]()
guard let playsSnapShot = playSnap.children.allObjects as? [DataSnapshot] else { return }
for play in playsSnapShot {
print(play)
let key = play.key
let sport = play.childSnapshot(forPath: "sports").value as? String ?? ""
let winLoss = play.childSnapshot(forPath: "winLoss").value as? String ?? ""
let teams = play.childSnapshot(forPath: "teams").value as? String ?? ""
let picks = play.childSnapshot(forPath: "picks").value as? String ?? ""
let date = play.childSnapshot(forPath: "date").value as? String ?? ""
let playsToSend = GameToSend(key: key, winLoss: winLoss, sport: sport, teams: teams, picks: picks, time: date )
plays.append(playsToSend)
}
handler(plays)
}
}
here i want to delete by uuid instead of key
func deleteDataforNotificationVC(key: String) {
PICKS.child(key).removeValue()
}
you delete like this id here udid:
func authenticateDeleteUserToken(email: String, password: String,id: String) {
Auth.auth().signIn(withEmail: email, password: password) { user, error in
if let error = error {
// An error happened.
self.showAlert(withTitle: appConstants.KAppName.rawValue, message: error.localizedDescription)
} else {
// for User deletion.
user?.user.delete { error in
if let error = error {
// An error happened.
self.showAlert(withTitle: appConstants.KAppName.rawValue, message: error.localizedDescription)
} else { //delete perticular id like child
let ref = Database.database().reference(withPath: "Users")
ref.child(id).removeValue { error, _ in
//success
}
}
}
}
}
}
Im uploading my data like this:
By using these function:
extension Database {
func createPurchase (purchaseID : String, quantity: String, completion: #escaping (Error?) -> ()){
guard let uid = Auth.auth().currentUser?.uid else { return }
let userPostRef = Database.database().reference().child("purchases").child(uid) //taken off auto ID
let values = ["purchase" : purchaseID, "quantity" : quantity ] as [String: Any]
userPostRef.updateChildValues(values) { (err, ref) in
if let err = err {
print("Failed to save purchase to database", err)
completion(err)
return
}
completion(nil)
}
}
}
.
In Viewcontroller 1:
func callID (){
let itemCount = CartController.shared.items.count
for i in 0...itemCount-1 {
let quantity = CartController.shared.items[i].quantity
let quantity1 = String(quantity)
let item = CartController.shared.items[i].product.id
Database.database().createPurchase(purchaseID: item, quantity: quantity1 ) { (err) in
if err != nil {
print("error uploading purchase to Firebase ")
return
}
}
}
}
callID uses createPurchase to take the sku number of each product and its quantity and uploads to firebase.
However, it overrides what was previously uploaded. So when I load more than 1 product. It only leaves the last products sku and quantity.
For this example, I started with 3 product, but only 1 (the last one) got uploaded.
How can I upload all the data. i.e stop this overide?
Here is how Im retrieving it:
extension Database {
func fetchPurchase(withUID uid: String, completion: #escaping (Purchase) -> ()) {
Database.database().reference().child("purchases").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
guard let userDictionary = snapshot.value as? [String: Any] else { return }
let purchase = Purchase(uid: uid, dictionary: userDictionary)
completion(purchase)
}) { (err) in
print("Failed to fetch purchase from database:", err)
}
}
}
.
In viewcontroller 2:
struct Purchase {
let uid: String
let purchases: String
let quantities: String
init(uid: String, dictionary: [String: Any]) {
self.uid = uid
self.purchases = dictionary["purchase"] as? String ?? ""
self.quantities = dictionary["quantity"] as? String ?? ""
}
}
var myPurchases: [Purchase] = []
private func fetchPurchaseForCurrentUser() {
guard let currentLoggedInUserId = Auth.auth().currentUser?.uid else { return }
Database.database().fetchPurchase(withUID: currentLoggedInUserId, completion: { (purchases) in
self.myPurchases.append(purchases)
print("myPurchases", self.myPurchases)
})
}
This is the printout I get:
myPurchases [myShop.Purchase(uid: "Tgb9MyxTfdTRd9tQhInsjNRXoPL2", purchases: "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0Lzk4OTUzMDk2OTk=", quantities: "2")]
This only shows the one product, however Im needing to have multiple products.
Please Help!
EDIT:
This is a screenshot of when I use ChildByAutoId().
I get all products (2 in this case).
But I am unable to retrieve the information from the snapshot and set to my text fields?
Prepare an array from multiple records, sample code:
var myPurchases: [Purchase] = []
for (key, value) in userDictionary {
guard let dic = value as? [String: Any] else {
continue
}
let purchaseModel = Purchase(uid: key, dictionary: dic)
myPurchases.append(purchaseModel)
}
I'm having a hard time trying to retrieve both the postId and commentId at the same time.
The goal is to allow a user to delete their own comment on a post.
Here is the Comment Struct, below is a the function that should delete the users comment, however for some reason I can only return the commentId and not the postId. So the comment is not deleted when clicked.
The postId will = nil if I run a break point in the final like of deleteComment, but if I run a break point on the final line of func fetchComment the postId will return whatever the postId is for the post.
struct Comment {
var commentId: String!
let user: User
var creationDate: Date!
let text: String
let uid: String!
init(commentId: String!,user: User, dictionary: [String: Any]) {
self.commentId = commentId
self.user = user
self.text = dictionary["text"] as? String ?? ""
self.uid = dictionary["uid"] as? String ?? ""
if let creationDate = dictionary["creationDate"] as? Double {
self.creationDate = Date(timeIntervalSince1970: creationDate)
}
}
var post: Post?
func deleteComment() {
guard let postId = self.post?.postId else { return }
guard let commentId = self.commentId else { return }
let commentsRef = Database.database().reference().child("comments")
commentsRef.child(postId).child(commentId).removeValue()
}
Here is how comments are fetched
var comments = [Comment]()
func fetchComments() {
guard let postId = self.post?.postId else { return }
let ref = Database.database().reference().child("comments").child(postId)
ref.observe(.childAdded, with: { (snapshot) in
let commentId = snapshot.key
//print(commentId)
guard let dictionary = snapshot.value as? [String: Any] else { return }
guard let uid = dictionary["uid"] as? String else { return }
Database.fetchUserWithUID(with: uid, completion: { (user) in
let comment = Comment(commentId: commentId, user: user, dictionary: dictionary)
self.comments.append(comment)
self.collectionView?.reloadData()
})
}) { (err) in
print("Failed to observe comments")
}
}
Also, here is the code when users submit a comment
func didSubmit(for comment: String) {
guard let uid = Auth.auth().currentUser?.uid else { return }
print("post id:", self.post?.postId ?? "")
print("Inserting comment:", comment)
let postId = self.post?.postId ?? ""
let values = ["text": comment, "creationDate": Date().timeIntervalSince1970, "uid": uid] as [String : Any]
Database.database().reference().child("comments").child(postId).childByAutoId().updateChildValues(values) { (err, ref) in
if let err = err {
print("Failed to insert comment:", err)
return
}
self.uploadCommentNotificationToServer()
if comment.contains("#") {
self.uploadMentionNotification(forPostId: postId, withText: comment, isForComment: true)
}
self.containerView.clearCommentTextView()
}
}
Json for comments via firebase
"comments" : {
"-Lord0UWPkh5YdGIHtAO" : {
"-Lp7AQzHccme5RcRsyDd" : {
"creationDate" : 1.568874020882821E9,
"text" : "Wow Cool!",
"uid" : "wELwYnMGxxW0LJNRKBuuE2BUaV93"
}
},
"-LowvCk-agvJbK0VF-Bq" : {
"-LpKm1NcgOsXhwj6soxE" : {
"creationDate" : 1.569102243436777E9,
"text" : "Nice!",
"uid" : "wELwYnMGxxW0LJNRKBuuE2BUaV93"
},
One option is to make postId a property in the Comment struct and add it to the init method, this way you will always has access to it
struct Comment {
let postId: String
var commentId: String!
let user: User
var creationDate: Date!
let text: String
let uid: String!
init(commentId: String!,user: User, postIdentifier: String, dictionary: [String: Any]) {
self.commentId = commentId
self.user = user
self.postId = postIdentifier
...
I am trying to allow users to delete comments upon pressing the delete button. When comments are submitted, they're created using autoId and the header of the node will be the postId to see what post they commented on.
"comments" : {
"-LmfZZis5ovtBwfm_4xR" : {
"-LoHu5Qv3BmuHTsSlthj" : {
"creationDate" : 1.567980283717026E9,
"text" : "Kkkk",
"uid" : "64r3dgTN6xMhHYhptFlsFWX0dLk2"
},
"-LoHuPohuQ3eUtDWL_G-" : {
"creationDate" : 1.567980367209054E9,
"text" : " Ok",
"uid" : "64r3dgTN6xMhHYhptFlsFWX0dLk2"
}
}
},
I do not know how to retrieve the autoId so current logged in users can delete their comments. Here is the code for submission
func didSubmit(for comment: String) {
guard let uid = Auth.auth().currentUser?.uid else { return }
print("post id:", self.post?.postId ?? "")
print("Inserting comment:", comment)
let postId = self.post?.postId ?? ""
let values = ["text": comment, "creationDate": Date().timeIntervalSince1970, "uid": uid] as [String : Any]
Database.database().reference().child("comments").child(postId).childByAutoId().updateChildValues(values) { (err, ref) in
if let err = err {
print("Failed to insert comment:", err)
return
}
self.uploadCommentNotificationToServer()
if comment.contains("#") {
self.uploadMentionNotification(forPostId: postId, withText: comment, isForComment: true)
}
self.containerView.clearCommentTextView()
}
}
Comment struct
struct Comment {
var commentId: String!
let user: User
var creationDate: Date!
let text: String
let uid: String!
init(commentId: String!,user: User, dictionary: [String: Any]) {
self.commentId = commentId
self.user = user
self.text = dictionary["text"] as? String ?? ""
self.uid = dictionary["uid"] as? String ?? ""
if let creationDate = dictionary["creationDate"] as? Double {
self.creationDate = Date(timeIntervalSince1970: creationDate)
}
}
var post: Post?
func deleteComment() {
guard let postId = self.post?.postId else { return }
let commentsRef = Database.database().reference().child("comments")
commentsRef.child(postId).child(commentId).removeValue()
}
}
Code to fetch the comments
var comments = [Comment]()
func fetchComments() {
guard let postId = self.post?.postId else { return }
let ref = Database.database().reference().child("comments").child(postId)
ref.observe(.childAdded, with: { (snapshot) in
let commentId = snapshot.key
guard let dictionary = snapshot.value as? [String: Any] else { return }
guard let uid = dictionary["uid"] as? String else { return }
Database.fetchUserWithUID(with: uid, completion: { (user) in
let comment = Comment(commentId: commentId, user: user, dictionary: dictionary)
self.comments.append(comment)
self.collectionView?.reloadData()
})
}) { (err) in
print("Failed to observe comments")
}
}
Thanks!
To be able to delete a node, you must know the full path to that node.
There are two ways to know the key of the product you want to delete:
You've passed it along your app from the moment when you loaded the data.
You have some other value that allows you to perform a query on the database to look up the key.
The first option is the most common, as you'll typically be loading the data from the database already to display it to the user. In that case you should "simply" pass the key of the data along when displaying the value.
Once you have the key of the product/child node, you can delete it with:
let postId = "-LmfZZis5ovtBwfm_4xR"
let commentId = "-LoHu5Qv3BmuHTsSlthj"
let commentsRef = Database.database().reference().child("comments")
commentsRef.child(postId).child(commentId).removeValue()