SwiftUI: Value of type 'DocumentSnapshot?' has no member 'document' - swift

When trying to fetch a user, I am getting the error: "Value of type 'DocumentSnapshot?' has no member 'document'". The error occurs on the line that starts "let uid....".
import SwiftUI
import Firebase
// Global Refernce
let ref = Firestore.firestore()
func fetchUser(uid: String,completion: #escaping (UserModel) -> ()){
ref.collection("Users").document(uid).getDocument { (doc, err) in
guard let user = doc else{return}
let username = user.data()?["username"] as? String ?? "No Username"
let pic = user.data()?["imageurl"] as? String ?? "No image URL"
let bio = user.data()?["bio"] as? String ?? "No bio"
let uid = doc.document.data()["uid"] as! String ??
DispatchQueue.main.async {
completion(UserModel(username: username, pic: pic, bio: bio, uid: uid))
}
}
}

if uid is a field like others username and imageurl then use
let uid = user.data()["uid"] as? String ?? ""
if you have made that uid as id of the document then use
let uid = doc.documentID
See Docs

Related

Must be a non-empty string and not contain '.' '#' '$' '[' or ']''

Please help! I am experiencing an app crash.
public enum memberships {
case noMembership
case paid
case freeTrial
case trialExpired
}
public class DataManager {
private static let uuid = UIDevice.current.identifierForVendor!.uuidString
private static let user = Auth.auth().currentUser
private static let userRef = Database.database().reference().child("Users").child(user?.uid ?? "")
static var currentStatus: memberships? = nil
/**
Get's the current user's info from Firebase
and returns the info as a User object
*/
class func getUser(completion: #escaping (User?) -> ()) {
userRef.observeSingleEvent(of: .value, with: { (snapshot) in
if let value = snapshot.value as? [String: Any] {
// UIPasteboard.general.string = uuid
let uuid = snapshot.key
let name = value["name"] as? String ?? ""
let email = value["email"] as? String ?? ""
let dateJoined = value["dateJoined"] as? String ?? ""
let membershipString = value["membership"] as? String
let alertsStartTime = value["alertsStartTime"] as? String ?? ""
let alertsEndTime = value["alertsEndTime"] as? String ?? ""
let alertsFrequency = value["alertsFrequency"] as? Int ?? 1
let alertsType = value["alertsType"] as? String ?? ""
let isEnable = value["isEnable"] as? Bool ?? true
//Gets users current membership
var membershipStatus: memberships!
if membershipString == "Paid" {
membershipStatus = .paid
}else if membershipString == "NoMembership" {
membershipStatus = .noMembership
}else{
membershipStatus = Utils.getUserMembershipStatus(dateJoined: dateJoined)
}
let user = User(uuid: uuid, name: name, email: email, dateJoined: dateJoined, membership: membershipStatus, alertsStartTime: alertsStartTime, alertsEndTime: alertsEndTime, alertsType: alertsType, alertsFrequency: alertsFrequency, isEnable: isEnable)
completion(user)
}else{
completion(nil)
}
}) { (error) in
print(error.localizedDescription)
completion(nil)
}
}
Your user object is empty. So user?.uid is nil. Which means child(user?.uid ?? "") -> child("").
Firebase does not accept empty strings as key values (It also does not accepts strings which includes '.' '#' '$' '[' or ']'' as keys).
So in your case make sure user is logged or use different key value.

SwiftUI - Firebase: Value of type 'String' has no member 'documentID'

When I try to get user data from firebase I have an error. The error message is:
Value of type 'String' has no member 'documentID'
The line with the error is the line fetchUser(uid: uid.documentID) { (user) in:
let title = doc.document.data()["title"] as? String ?? "No Title"
let time = doc.document.data()["time"] as? Timestamp ?? Timestamp(date: Date())
let pic = doc.document.data()["url"] as? String ?? "No URL"
let uid = doc.document.data()["uid"] as? String ?? ""
// getting user Data...
fetchUser(uid: uid.documentID) { (user) in
And this is my FetchUser model:
// Global Refernce
let ref = Firestore.firestore()
func fetchUser(uid: String,completion: #escaping (UserModel) -> ()){
ref.collection("Users").document(uid).getDocument { (doc, err) in
guard let user = doc else{return}
let username = user.data()?["username"] as? String ?? "No Username"
let pic = user.data()?["imageurl"] as? String ?? "No image URL"
let bio = user.data()?["bio"] as? String ?? "No bio"
let uid = user.data()?["uid"] as? String ?? ""
DispatchQueue.main.async {
completion(UserModel(username: username, pic: pic, bio: bio, uid: uid))
}
}
}
Below is code to that checks the users uid. On the line that starts "ref.collection..." the error "Cannot find 'uid' in scope" is thrown.
func checkUser(){
let ref = Firestore.firestore()
if let currentUser = Auth.auth().currentUser {
let uid = currentUser.uid
} else {
print("No Authenticated User")
return
}
ref.collection("Users").whereField("uid", isEqualTo: uid).getDocuments { (snap, err) in
if err != nil{
// No Documents..
// No User Found...
self.registerUser.toggle()
self.isLoading = false
return
}
if snap!.documents.isEmpty{
self.registerUser.toggle()
self.isLoading = false
return
}
self.log_Status = true
}
}
Let me take the first part of your code to show where the issue is. Note how much easier it is to read when properly formatted
func checkUser() {
let ref = Firestore.firestore()
if let currentUser = Auth.auth().currentUser {
//NOTE! Note that this area is encapsulated with brackets { and }
//That means it's is own 'space' and anything defined in this area
//only exists in this area
let uid = currentUser.uid //<- uid only exists here
} else {
print("No Authenticated User")
return
}
//uid no longer exists and cannot be referenced
// e.g. it's not in 'scope' at this point
ref.collection("Users").whereField("uid", isEqualTo: uid)
However, if you look at where the let ref = Firestore line is located, it's at the top level within the checkUser function and will exist throughout the function.
There are many way to do this; here's one using a guard statement
func checkUser() {
let ref = Firestore.firestore()
guard let currentUser = Auth.auth().currentUser else {
print("no user!")
return
}
// currentUser flows through to here because it was created with
// a guard statement, so now we know it's populated and can
// get the uid property value from it
let uid = currentUser.uid
ref.collection("Users").whereField("uid", isEqualTo: uid)
guard is pretty neat in that it not only allows you to instantiate a var while a the same time as protecting your code from a nil situation, it also allows the var to flow through to the code following the guard.
I'm writting this answer as a community wiki, since the issue was resolved from the comments section, in order to provide a proper response to the issue reported.
The error came while trying to get the uid as fetchUser(uid: uid.documentID), instead the correct way is by doing fetchUser(uid: uid)
Then an error mentioning Document path cannot be empty appeared, which was mainly due to the fact that no entries with were loaded, the best way to avoid this is to load documents on the consulted path without nil values

Ambiguous use of 'subscript(_:)' when trying to retrieve users from my FireBase Database

Like the description says I'm trying to retrieve users info from my Firebase Database and append them to my array I created but im getting the "Ambiguous use of 'subscript(_:)'" error in my for in loop
˚
func getArtist(){
let reference = Database.database().reference()
reference.child("users").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in
let users = snapshot.value as! [String : AnyObject]
self.artistArray.removeAll()
for (_,value) in users {
if let artistId = value["uid"] as? String {
if artistId != Auth.auth().currentUser!.uid{
let artistShown = Artist()
if let userName = value["full_name"] as? String, let imagePath = value["urlToImage"] as? String {
artistShown.UserName = userName
artistShown.pathToImage = imagePath
artistShown.ArtistId = artistId
self.artistArray.append(artistShown)
}
}
}
}
self.ArtistView.reloadData()
})
reference.removeAllObservers()
}
˚
I've also attached A ScreenShot to show Where I'm getting the error
Error message

Swift, How to Get Completion Handler working as I Wish?

I am fetching user information from Firebase and my goal is to fetch a batch of users and then display them on the screen one at a time in a card stack. To do this i use a completion handler. However my code inside the completion handler runs before the fetch of all users is done.
Thank you for any help.
Here is my code. I want "fetchOneUser()" to run when "fetchAllUsers" is done:
fetchAllUsers(completion: { message in
print(message)
print("FetchOneUser")
self.fetchOneUser()
})
Here is fetchAllUser function:
func fetchAllUsers(completion: #escaping (_ message: String) -> Void){
//User or advertiser?
Database.database().reference(withPath: "Advertiser").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists(){
myAdvertiserVar.advertiser = true
self.currentUserKind = "Advertiser"
self.otherUserKind = "Users"
}
else{
self.currentUserKind = "Users"
self.otherUserKind = "Advertiser"
}
// Fetch
let query = self.ref?.child(self.otherUserKind).queryOrdered(byChild: "email")
query?.observeSingleEvent(of: .value) {
(snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
let id = child.key
//If Already Accepted, don't fetch
Database.database().reference(withPath: self.currentUserKind).child(self.uid).child("Accepted").child(id).observeSingleEvent(of: .value, with: {(accepted) in
if accepted.exists(){
print("\(id) är redan Accepted")
}
else{
if myAdvertiserVar.advertiser == true{
let value = child.value as? NSDictionary
let username = value?["Username"] as? String
let occupation = value?["Occupation"] as? String
let age = value?["Age"] as? String
let bio = value?["Bio"] as? String
let email = value?["email"] as? String
let user = User(id: id, username: username, occupation: occupation, age: age, bio: bio, email: email)
self.usersArray.append(user)
}
else{
let value = child.value as? NSDictionary
let username = value?["Owner"] as? String
let occupation = value?["Location"] as? String
let age = value?["Rent"] as? String
let bio = value?["About"] as? String
let email = value?["email"] as? String
let user = User(id: id, username: username, occupation: occupation, age: age, bio: bio, email: email)
self.usersArray.append(user)
}
}
})
}
print(self.usersArray.count)
completion("Users list fetched")
}
})
}
You need to use DispatchGroup as the inner calls are asynchronous
func fetchAllUsers(completion: #escaping (_ message: String) -> Void){
//User or advertiser?
Database.database().reference(withPath: "Advertiser").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists(){
myAdvertiserVar.advertiser = true
self.currentUserKind = "Advertiser"
self.otherUserKind = "Users"
}
else{
self.currentUserKind = "Users"
self.otherUserKind = "Advertiser"
}
// Fetch
let query = self.ref?.child(self.otherUserKind).queryOrdered(byChild: "email")
query?.observeSingleEvent(of: .value) {
(snapshot) in
let g = DispatchGroup()
for child in snapshot.children.allObjects as! [DataSnapshot] {
let id = child.key
//If Already Accepted, don't fetch
g.enter()
Database.database().reference(withPath: self.currentUserKind).child(self.uid).child("Accepted").child(id).observeSingleEvent(of: .value, with: {(accepted) in
if accepted.exists(){
print("\(id) är redan Accepted")
}
else{
if myAdvertiserVar.advertiser == true{
let value = child.value as? NSDictionary
let username = value?["Username"] as? String
let occupation = value?["Occupation"] as? String
let age = value?["Age"] as? String
let bio = value?["Bio"] as? String
let email = value?["email"] as? String
let user = User(id: id, username: username, occupation: occupation, age: age, bio: bio, email: email)
self.usersArray.append(user)
}
else{
let value = child.value as? NSDictionary
let username = value?["Owner"] as? String
let occupation = value?["Location"] as? String
let age = value?["Rent"] as? String
let bio = value?["About"] as? String
let email = value?["email"] as? String
let user = User(id: id, username: username, occupation: occupation, age: age, bio: bio, email: email)
self.usersArray.append(user)
}
}
g.leave()
})
}
g.notify(queue: .main, execute: {
print(self.usersArray.count)
completion("Users list fetched")
})
}
})
}
Based on Firebase documentation:
Firebase use refrence() method to get a database refrence for the root of your real time database asynchronous.
this means that result takes more time to fetch than for loop, in this situation your for loop finishes and completion block calls and takes you out of method, then result of your request will return.
your code should look like
var firebaseDatabaseRefrence: DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
Database.database().reference(withPath: self.currentUserKind)
}
func someMethod() {
self.firebaseDatabaseRefrence
.child(self.uid)
.child("Accepted")
.child(id).observeSingleEvent(of: .value, with: {(accepted) in
}

How to fetch limited amount of users from Firebase

I am doing a card stack swipe app with users similar to Tinder.
I want to fetch a batch of 10 users from Firebase. I have used queryLimited(toFirst: 10) for this but later in my function i won't fetch the users who have already been accepted(swiped right). This means that if the first 10 users from Firebase already have been accepted nobody will be fetched. I want to fetch the first 10 users who hasn't been accepted.
Does anyone have a great solution for this?
Thank you.
FetchUsers code for fetching users from Firebase:
func fetchAllUsers(completion: #escaping (_ message: String) -> Void){
//User or advertiser?
Database.database().reference(withPath: "Advertiser").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists(){
myAdvertiserVar.advertiser = true
self.currentUserKind = "Advertiser"
self.otherUserKind = "Users"
}
else{
myAdvertiserVar.advertiser = false
self.currentUserKind = "Users"
self.otherUserKind = "Advertiser"
}
// Fetch
let query = self.ref?.child(self.otherUserKind).queryOrdered(byChild: "email").queryLimited(toFirst: 10)
query?.observeSingleEvent(of: .value) {
(snapshot) in
let g = DispatchGroup()
for child in snapshot.children.allObjects as! [DataSnapshot] {
let id = child.key
//If Already Accepted, don't fetch
g.enter()
Database.database().reference(withPath: self.currentUserKind).child(self.uid).child("Accepted").child(id).observeSingleEvent(of: .value, with: {(accepted) in
if accepted.exists(){
print("\(id) är redan Accepted")
}
else{
if myAdvertiserVar.advertiser == true{
let value = child.value as? NSDictionary
let username = value?["Username"] as? String
let occupation = value?["Occupation"] as? String
let age = value?["Age"] as? String
let bio = value?["Bio"] as? String
let email = value?["email"] as? String
let user = User(id: id, username: username, occupation: occupation, age: age, bio: bio, email: email)
self.usersArray.append(user)
}
else{
let value = child.value as? NSDictionary
let username = value?["Owner"] as? String
let occupation = value?["Location"] as? String
let age = value?["Rent"] as? String
let bio = value?["About"] as? String
let email = value?["email"] as? String
let user = User(id: id, username: username, occupation: occupation, age: age, bio: bio, email: email)
self.usersArray.append(user)
}
}
g.leave()
})
}
g.notify(queue: .main, execute: {
print(self.usersArray.count)
completion("Users list fetched")
})
}
})
}