Update data stored in Firebase using MVVM nested models - swift

I built an MVVM architecture to support my app which is supposed to control the pipeline between the frontend and my firebase database. Initially, I successfully implemented the entire work by coding totally in the frontend, but there are lots of bugs when I encapsulated them into a function.
For example, the next sheet will be presented when the currently presented sheet gets dismissed. Sometimes I needed to wait for a long time until the app is unfrozen. Even worse, the app crashed down when I clicked the button.
I heard that nested models don't work yet if SwiftUI is in use (reference). However, I just cannot come up with a better solution if my classes are untested.
// This is Model
import Foundation
import SwiftUI
struct userModel {
var uid = UUID()
var name = ""
var bio = ""
var interest = ""
var level = 1
var xp = 0
var email = ""
var image: Data = Data(count: 0)
init() {
}
init(_ name:String, _ xp: Int) {
self.name = name
self.xp = xp
self.level = self.xp2Level(xp: xp)
}
func xp2Level(xp:Int) -> Int {
if xp < 9500 {
return xp / 500 + 1
}
else if xp < 29500 {
return (xp - 9500) / 1000 + 1
}
else {
return (xp - 29500) / 2000 + 1
}
}
}
// This is ViewModel
import Foundation
import SwiftUI
import Firebase
class userViewModel: ObservableObject {
#Published var user: userModel = userModel()
#Published var isLoading = false
#AppStorage("status") var status = false
private var ref = Firestore.firestore()
private let store = Storage.storage().reference()
var picker = false
func updateXP(completion: #escaping () -> Int) -> Int {
guard let uid = Auth.auth().currentUser?.uid else {
return 0
}
// catch the information of the current user
let db = ref.collection("Users")
db.addSnapshotListener { [self] (querySnapshot, error) in
guard (querySnapshot?.documents) != nil else {
print("Document is empty")
return
}
let docRef = db.document(uid)
docRef.getDocument { (snapshot, error) in
if let doc = snapshot,
let xp = doc.get("xp") as? Int {
self.user.xp = xp
}
}
}
return completion()
}
func updateLevel(completion: #escaping () -> Int) -> Int {
guard let uid = Auth.auth().currentUser?.uid else {
return 1
}
// catch the information of the current user
let db = ref.collection("Users")
db.addSnapshotListener { [self] (querySnapshot, error) in
guard (querySnapshot?.documents) != nil else {
print("Document is empty")
return
}
let docRef = db.document(uid)
docRef.getDocument { (snapshot, error) in
if let doc = snapshot,
let level = doc.get("level") as? Int {
self.user.level = level
}
}
}
return completion()
}
func updateName (completion: #escaping () -> String) -> String {
guard let uid = Auth.auth().currentUser?.uid else {
return ""
}
// catch the information of the current user
let db = ref.collection("Users")
db.addSnapshotListener { [self] (querySnapshot, error) in
guard (querySnapshot?.documents) != nil else {
print("Document is empty")
return
}
let docRef = db.document(uid)
docRef.getDocument { (snapshot, error) in
if let doc = snapshot,
let name = doc.get("username") as? String {
self.user.name = name
}
}
}
return completion()
}
func updateBio (completion: #escaping () -> String) -> String {
guard let uid = Auth.auth().currentUser?.uid else {
return ""
}
// catch the information of the current user
let db = ref.collection("Users")
db.addSnapshotListener { [self] (querySnapshot, error) in
guard (querySnapshot?.documents) != nil else {
print("Document is empty")
return
}
let docRef = db.document(uid)
docRef.getDocument { (snapshot, error) in
if let doc = snapshot,
let bio = doc.get("bio") as? String {
self.user.bio = bio
}
}
}
return completion()
}
func updateInterest (completion: #escaping () -> String) -> String {
guard let uid = Auth.auth().currentUser?.uid else {
return ""
}
// catch the information of the current user
let db = ref.collection("Users")
db.addSnapshotListener { [self] (querySnapshot, error) in
guard (querySnapshot?.documents) != nil else {
print("Document is empty")
return
}
let docRef = db.document(uid)
docRef.getDocument { (snapshot, error) in
if let doc = snapshot,
let interest = doc.get("interest") as? String {
self.user.interest = interest
}
}
}
return completion()
}
func updatePhoto (completion: #escaping () -> Data) -> Data {
guard let uid = Auth.auth().currentUser?.uid else {
return Data(count: 0)
}
// catch the information of the current user
let db = ref.collection("Users")
db.addSnapshotListener { [self] (querySnapshot, error) in
guard (querySnapshot?.documents) != nil else {
print("Document is empty")
return
}
let docRef = db.document(uid)
docRef.getDocument { (snapshot, error) in
if snapshot != nil {
let imageRef = store.child("profile_Photos").child(uid)
imageRef.getData(maxSize: 1000 * 64 * 64, completion: { (data, error) in
if let error = error {
print("Encountered error: \(error) when getting image")
self.user.image = Data(count: 0)
} else if let data = data,
!data.isEmpty{
// self.currentUser.image = Image(uiImage: UIImage(data: data)!).resizable()
self.user.image = data
} else {
// self.currentUser.image = Image(systemName: "person").resizable()
self.user.image = Data(count: 0)
}
})
} else if let error = error {
print(error)
}
}
}
return completion()
}
public func getXP() -> Int{
updateXP {
return (self.user.xp) as Int
}
}
public func getLevel() -> Int {
updateLevel(completion: {
return (self.user.level) as Int
})
}
public func getName() -> String {
updateName(completion: {
return (self.user.name) as String
})
}
public func getBio() -> String {
updateBio(completion: {
return (self.user.bio) as String
})
}
public func getInterest() -> String {
updateInterest(completion: {
return (self.user.interest) as String
})
}
public func getPhoto() -> Data {
updatePhoto(completion: {
return (self.user.image) as Data
})
}
func updatePersonalInfo() {
//sending user data to Firebase
let uid = Auth.auth().currentUser?.uid
isLoading = true
self.uploadImage(imageData: self.getPhoto(), path: "profile_Photos") { (url) in
self.ref.collection("Users").document(uid ?? "").setData([
"uid": uid ?? "",
"imageurl": url,
"username": self.user.name,
"bio": self.user.bio,
"interest" : self.user.interest
], merge: true) { (err) in
if err != nil{
self.isLoading = false
return
}
self.isLoading = false
// success means settings status as true...
self.status = true
}
}
}
func increaseXPnLV() {
//sending user data to Firebase
let uid = Auth.auth().currentUser!.uid
let docRef = ref.collection("Users").document(uid)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
docRef.updateData(["xp": FieldValue.increment(Int64(50))])
// update level
let xp = document.data()!["xp"] as! Int
docRef.updateData(["level": self.user.xp2Level(xp: xp)])
} else {
print("Document does not exist")
}
}
}
func uploadImage(imageData: Data, path: String, completion: #escaping (String) -> ()){
let storage = Storage.storage().reference()
let uid = Auth.auth().currentUser?.uid
storage.child(path).child(uid ?? "").putData(imageData, metadata: nil) { (_, err) in
print("imageData: \(imageData)")
if err != nil{
completion("")
return
}
// Downloading Url And Sending Back...
storage.child(path).child(uid ?? "").downloadURL { (url, err) in
if err != nil{
completion("")
return
}
completion("\(url!)")
}
}
}
}
// This is View
import SwiftUI
import CoreData
import Firebase
import FirebaseFirestore
struct Goals: View {
let current_user_id = Auth.auth().currentUser?.uid
#State private var showingAlert = false
var ref = Firestore.firestore()
#StateObject var currentUser: userViewModel
#StateObject var homeData = HomeViewModel()
#State var txt = ""
#State var edge = UIApplication.shared.windows.first?.safeAreaInsets
#FetchRequest(entity: Goal.entity(), sortDescriptors: [NSSortDescriptor(key: "date",
ascending: true)], animation: .spring()) var results : FetchedResults<Goal>
// let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
#State private var greeting : String = "Hello"
#Environment(\.managedObjectContext) var context
var body: some View {
ForEach(results){goal in
Button(action: {
context.delete(goal)
try! context.save()
if current_user_id != nil {
currentUser.updateXPnLV()
self.showingAlert = true
}
}, label: Text("Something")
)
.alert(isPresented: $showingAlert) {
() -> Alert in
Alert(title: Text("Congratulations!"), message: Text("You completed a goal today, XP+50!"), dismissButton: .default(Text("OK")))
}
}
}
}
EDIT
Another error I saw is AttributeGraph precondition failure: attribute failed to set an initial value: 805912, ForEachChild<Array<userInfoModel>, ObjectIdentifier, HStack<VStack<HStack<TupleView<(Text, Divider, Text)>>>>>.

AppStorage is for use in a View while it may appear to be working all the SwiftUI wrappers with the exception of #Published inside an ObservableObject seem to be unreliable outside of a struct that is a View.
https://developer.apple.com/documentation/swiftui/appstorage
As a standard practice all your class and struct should be capitalized so change class CurrentUserViewModel andclass UserInfoModel
Also, change #StateObject var currentUser: currentUserViewModel to #StateObject var currentUser: CurrentUserViewModel = CurrentUserViewModel()
The initialization is the most important part that is missing.
Everything in the ForEach is just floating it isn't within a variable, function or inside the body. Where is your body?
This is probably what the error is talking about. wrap all of that code in a body
var body: some View {
//All the code for the ForEach
}
Your Button seems to be missing a title or label
Remove this line
() -> Alert in
I am sure there are other little things. I suggest you start from scratch in this View and you start putting in code line by line.
Here is a starting point. The Firebase part needs quite a but of work but you should be able to get started by focusing on the code that I commented out and removing the code to mimic a response from Firebase.
All of this is in the FirebaseManager class
Once this is working the rest will work.
The code as is works so you can see it in action with the fake responses
///Keep all the Firebase Code HERE
class FirebaseManager{
//private var ref = Firestore.firestore()
//private let store = Storage.storage().reference()
func retrieveFromDB(collectionName: String, variableName: String, completion: #escaping (Result<Any, Error>) -> Void) {
print(#function)
//This is sample code, likely has errors because I dont have Firebase setup but you can see the logic so you can touch up
// guard let uid = Auth.auth().currentUser?.uid else {
// completion(.failure(FirebaseError.notLoggedIn))
// return
// }
// catch the information of the current user
// let db = ref.collection(collectionName)
// db.addSnapshotListener { [self] (querySnapshot, error) in
//
// if let error = error{
// completion(.failure(error))
// return
// }
// guard (querySnapshot?.documents) != nil else {
// print("Document is empty")
// completion(.failure(FirebaseError.emptyDocument))
// return
// }
// let docRef = db.(document(uid)
//
// docRef.getDocument { (snapshot, error) in
// if let error = error{
// completion(.failure(error))
// return
// }
//
// completion(.success(snapshot.get(variableName)))
// }
// }
//For sample purposes I will mimic response remove this in your actual code
DispatchQueue.main.async {
if variableName == "xp" || variableName == "level"{
completion(.success(Int.random(in: 0...200)))
}else{
let strings = ["apple", "orange", "banana", "kiwi", "startfruit"]
completion(.success(strings.randomElement()!))
}
}
}
///For Int variables
func retrieveFromUsers(variableName: String, completion: #escaping (Result<Int, Error>) -> Void) {
print(#function)
retrieveFromDB(collectionName: "Users", variableName: variableName, completion: {result in
switch result {
case .success(let value):
let xp = value as? Int
if xp != nil{
completion(.success(xp!))
}else{
completion(.failure(FirebaseError.wrongType))
}
return
case .failure(let error):
print(error)
completion(.failure(error))
}
})
}
///For String variables
func retrieveUserProperty(variableName: String, completion: #escaping (Result<String, Error>) -> Void) {
print(#function)
retrieveFromDB(collectionName: "Users", variableName: variableName, completion: {result in
switch result {
case .success(let value):
let username = value as? String
if username != nil{
completion(.success(username!))
}else{
completion(.failure(FirebaseError.wrongType))
}
return
case .failure(let error):
print(error)
completion(.failure(error))
}
})
}
func retrieveXP(completion: #escaping (Result<Int, Error>) -> Void) {
print(#function)
retrieveFromUsers(variableName: "xp", completion: completion)
}
func retrieveLevel(completion: #escaping (Result<Int, Error>) -> Void) {
print(#function)
retrieveFromUsers(variableName: "level", completion: completion)
}
func retrieveName (completion: #escaping (Result<String, Error>) -> Void) {
print(#function)
retrieveUserProperty(variableName: "username", completion: completion)
}
func retrieveBio (completion: #escaping (Result<String, Error>) -> Void) {
print(#function)
retrieveUserProperty(variableName: "bio", completion: completion)
}
func retrieveInterest (completion: #escaping (Result<String, Error>) -> Void) {
print(#function)
retrieveUserProperty(variableName: "interest", completion: completion)
}
//Database code to retrieve Image needs to be added
func updateDB(collectionName: String, variableName: String, incrementBy: Int, completion: #escaping (Result<Int, Error>) -> Void) {
print(#function)
//sending user data to Firebase
// let uid = Auth.auth().currentUser!.uid
// let docRef = ref.collection(collectionName).document(uid)
// docRef.getDocument { (document, error) in
// if let document = document, document.exists {
// docRef.updateData([variableName: FieldValue.increment(incrementBy)])
//let newValue = document.data()![variableName] as! Int
// completion(.success(newValue))
// } else {
// completion(.failure(FirebaseError.documentDoesntExist))
// }
// }
//For sample purposes I will mimic response remove this in your actual code
DispatchQueue.main.async {
completion(.success(Int.random(in: 0...200) + incrementBy))
}
}
func updateDB(collectionName: String, variableName: String, value: String, completion: #escaping (Result<String, Error>) -> Void) {
print(#function)
//sending user data to Firebase
// let uid = Auth.auth().currentUser!.uid
// let docRef = ref.collection(collectionName).document(uid)
// docRef.getDocument { (document, error) in
// if let document = document, document.exists {
// docRef.updateData([variableName: value])
//let newValue = document.data()![variableName] as! Int
// completion(.success(newValue))
// } else {
// completion(.failure(FirebaseError.documentDoesntExist))
// }
// }
//For sample purposes I will mimic response remove this in your actual code
DispatchQueue.main.async {
let strings = ["apple", "orange", "banana", "kiwi", "startfruit"]
completion(.success(strings.randomElement()!))
}
}
func updateDB(collectionName: String, variableName: String, value: Int, completion: #escaping (Result<Int, Error>) -> Void) {
print(#function)
//sending user data to Firebase
// let uid = Auth.auth().currentUser!.uid
// let docRef = ref.collection(collectionName).document(uid)
// docRef.getDocument { (document, error) in
// if let document = document, document.exists {
// docRef.updateData([variableName: value])
//let newValue = document.data()![variableName] as! Int
// completion(.success(newValue))
// } else {
// completion(.failure(FirebaseError.documentDoesntExist))
// }
// }
//For sample purposes I will mimic response
DispatchQueue.main.async {
completion(.success(Int.random(in: 0...200)))
}
}
func updateUsers(variableName: String, value: String, completion: #escaping (Result<String, Error>) -> Void) {
print(#function)
updateDB(collectionName: "Users", variableName: variableName, value: value, completion: completion)
}
func updateUsers(variableName: String, value: Int, completion: #escaping (Result<Int, Error>) -> Void) {
print(#function)
updateDB(collectionName: "Users", variableName: variableName, value: value, completion: completion)
}
func updateUsers(variableName: String, incrementBy: Int, completion: #escaping (Result<Int, Error>) -> Void) {
print(#function)
updateDB(collectionName: "Users", variableName: variableName, incrementBy: incrementBy, completion: completion)
}
//Code to update Image will need to be added
}
Here is the rest
import SwiftUI
import CoreData
//Capitalized no other changes here
struct UserModel {
var uid = UUID()
var name = ""
var bio = ""
var interest = ""
var level = 1
var xp = 0
var email = ""
var image: Data = Data(count: 0)
init() {
print(#function)
}
init(_ name:String, _ xp: Int) {
print(#function)
self.name = name
self.xp = xp
self.level = self.xp2Level(xp: xp)
}
func xp2Level(xp:Int) -> Int {
print(#function)
if xp < 9500 {
return xp / 500 + 1
}
else if xp < 29500 {
return (xp - 9500) / 1000 + 1
}
else {
return (xp - 29500) / 2000 + 1
}
}
}
//This is to standardize what comes from your Firebase Code. Try to condense code that is duplicated
enum FirebaseError: Error {
case notLoggedIn
case emptyDocument
case wrongType
case documentDoesntExist
}
Capitalize
class UserViewModel: ObservableObject {
let alertVM = AlertViewModel.shared
#Published var user: UserModel = UserModel()
#Published var isLoading = false
//AppStorage wont work here
var status: Bool{
get{
UserDefaults.standard.bool(forKey: "status")
}
set{
UserDefaults.standard.set(newValue, forKey: "status")
}
}
//Separate all Firebase Code
let firebaseManager = FirebaseManager()
init() {
populateAllVariables()
}
func increaseXPnLV() {
print(#function)
//sending xp to Firebase
firebaseManager.updateUsers(variableName: "xp", incrementBy: 50, completion: {result in
switch result {
case .success(let newXp):
self.user.xp = newXp
//sending level to Firebase
self.firebaseManager.updateUsers(variableName: "level", value: self.user.xp2Level(xp: newXp), completion: {result in
switch result {
case .success(let newLevel):
print("newLevel = \(newLevel)")
self.user.level = newLevel
self.alertVM.scheduleAlert(title: "Congratulations!", message: "You completed a goal today, XP+50!")
return
case .failure(let error as NSError):
//Show alert here
self.alertVM.scheduleAlert(error: error)
print(error)
}
})
return
case .failure(let error):
//Show alert here
self.alertVM.scheduleAlert(error: error)
print(error)
}
})
}
func populateAllVariables() {
print(#function)
getXP()
getLevel()
getName()
getBio()
getInterest()
}
public func getXP() {
print(#function)
firebaseManager.retrieveXP(completion: {result in
switch result {
case .success(let xp):
self.user.xp = xp
case .failure(let error):
//Show alert here
self.alertVM.scheduleAlert(error: error)
print(error)
}
})
}
public func getLevel() {
print(#function)
firebaseManager.retrieveLevel(completion: {result in
switch result {
case .success(let level):
self.user.level = level
case .failure(let error):
//Show alert here
self.alertVM.scheduleAlert(error: error)
print(error)
}
})
}
public func getName() {
print(#function)
firebaseManager.retrieveName(completion: {result in
switch result {
case .success(let name):
self.user.name = name
case .failure(let error):
//Show alert here
self.alertVM.scheduleAlert(error: error)
print(error)
}
})
}
public func getBio() {
print(#function)
firebaseManager.retrieveBio(completion: {result in
switch result {
case .success(let bio):
self.user.bio = bio
case .failure(let error):
//Show alert here
self.alertVM.scheduleAlert(error: error)
print(error)
}
})
}
public func getInterest() {
print(#function)
firebaseManager.retrieveInterest(completion: {result in
switch result {
case .success(let interest):
self.user.interest = interest
case .failure(let error):
//Show alert here
self.alertVM.scheduleAlert(error: error)
print(error)
}
})
}
///This will need work
// public func getPhoto() -> Data {
// updatePhoto(completion: {
// return (self.user.image) as Data
// })
// }
//It is best to separate work from the View
func deleteGoal(moc: NSManagedObjectContext, goal: Goal) -> Bool{
print(#function)
var result = false
moc.performAndWait {
moc.delete(goal)
do{
try moc.save()
result = true
}catch{
self.alertVM.scheduleAlert(error: error)
result = false
}
}
return result
}
}
//This is to centralize alerts. When you are using the web there will be errors and therefore alerts that the user should be aware of
struct CustomAlert: Identifiable {
let id: UUID = UUID()
let title: String
let message: String
let dismissButtonTitle: String
}
//Again to centralize the alerts. I like putting this on the uppermost View so you can send alerts from anywhere
class AlertViewModel: ObservableObject {
//Singleton keeps everything connected
static let shared: AlertViewModel = AlertViewModel()
#Published var currentAlert: CustomAlert?
private init() {
//Required because you need to share the instance
}
//Use this for a custom message
func scheduleAlert(title: String = "ERROR", message: String, dismissButtonTitle: String = "OK") {
currentAlert = CustomAlert(title: title, message: message, dismissButtonTitle: dismissButtonTitle)
}
//Use this if you have a fully formed Error
func scheduleAlert(error: Error) {
let error = error as NSError
currentAlert = CustomAlert(title: "ERROR", message: (error.localizedFailureReason ?? "") + error.localizedDescription + (error.localizedRecoverySuggestion ?? ""), dismissButtonTitle: "OK")
}
}
struct Goals: View {
//The View should never be aware of where your data is stored. all Firebase code should be removed
#StateObject var currentUser: UserViewModel = UserViewModel()
//This observes the alerts that are sent from anywhere
#StateObject var alertVM: AlertViewModel = AlertViewModel.shared
//No code provided
//#StateObject var homeData = HomeViewModel()
#FetchRequest(entity: Goal.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Goal.date, ascending: true)], animation: .spring()) var results : FetchedResults<Goal>
#Environment(\.managedObjectContext) var context
var body: some View {
VStack{
Text("Name = " + currentUser.user.name.description)
Text("Level = " + currentUser.user.level.description)
Text("XP = " + currentUser.user.xp.description)
ForEach(results){goal in
Button(action: {
//There should be some kind of check here to make sure the goal got deleted
if currentUser.deleteGoal(moc: context, goal: goal){
//No code provided
//if current_user_id != nil {
currentUser.increaseXPnLV()
}
//}
}, label: {
//Missing Brackets
Text("Goal \(goal.name?.description ?? "") Completed")
})
//This gets presented from everywhere
.alert(item: $alertVM.currentAlert, content: {current in
Alert(title: Text(current.title), message: Text(current.message), dismissButton: .cancel(Text(current.dismissButtonTitle)))
})
}
}
}
}

Related

"FIRESTORE : Invalid document reference. Document references must have an even number of segments, but chats/GP6sgTdilUZql2XvZUxQhQLimhm1/chats has 3"

This is my second app. when l was try to send message l get this error :
Thread 1: "FIRESTORE INTERNAL ASSERTION FAILED: Invalid document reference. Document references must have an even number of segments, but chats/GP6sgTdilUZql2XvZUxQhQLimhm1/chats has 3"
this is my chat service
class ChatService: ObservableObject {
#Published var isLoading = false
#Published var chats: [Chat] = []
var listener: ListenerRegistration!
var recipientId = ""
static var chats = AuthService.storeRoot.collection("chats")
static var messages = AuthService.storeRoot.collection("messages")
static func conversation(sender: String, recipient: String) ->
CollectionReference {
return chats.document(sender).collection("chats").document(recipient).collection("conversation")
}
static func userMessages(userid: String) -> CollectionReference {
return messages.document(userid).collection("messages")
}
static func messagesId(senderId: String, recipientId: String) ->
DocumentReference {
return messages.document(senderId).collection("messages").document(recipientId)
}
func loadChats() {
self.chats = []
self.isLoading = true
self.getChats(userId: recipientId, onSuccess: {
(chats) in
if self.chats.isEmpty {
self.chats = chats
}
}, onError: {
(err) in
print("Error \(err)")
}, newChat: {
(chat) in
if !self.chats.isEmpty {
self.chats.append(chat)
}
}) {
(listener) in
self.listener = listener
}
}
func sendMessage(message: String, recipientId: String,
recipientProfile: String, recipientName: String, onSuccess:
#escaping()-> Void, onError: #escaping(_ error: String)-> Void) {
guard let senderId = Auth.auth().currentUser?.uid else {return}
guard let senderUsername = Auth.auth().currentUser?.displayName
else {return}
guard let senderProfile = Auth.auth().currentUser?.photoURL!.absoluteString else {return}
let messageId = ChatService.conversation(sender: senderId,
recipient: recipientId).document().documentID
let chat = Chat(messageId: messageId, textMessage: message,
profile: senderProfile, photoUrl: "", sender: senderId,
username: senderUsername, timestamp:
Date().timeIntervalSince1970, isPhoto: false)
guard let dict = try? chat.asDictionary() else {return}
ChatService.conversation(sender: senderId, recipient:
recipientId).document(messageId).setData(dict) {
(error) in
if error == nil {
ChatService.conversation(sender: recipientId, recipient:
senderId).document(messageId).setData(dict)
let senderMessage = Message(lastMessage: message,
username: senderUsername, isPhoto: false,
timestamp: Date().timeIntervalSince1970, userId:
senderId, profile: senderProfile)
let recipientMessage = Message(lastMessage: message,
username: recipientName, isPhoto: false,
timestamp: Date().timeIntervalSince1970, userId:
recipientId, profile: recipientProfile)
guard let senderDict = try? senderMessage.asDictionary()
else {return}
guard let recipientDict = try? recipientMessage.asDictionary()
else {return}
ChatService.messagesId(senderId: senderId, recipientId: recipientId).setData(senderDict)
ChatService.messagesId(senderId: recipientId, recipientId: senderId).setData(recipientDict)
onSuccess()
} else {
onError(error!.localizedDescription)
}
}
}
func sendPhotoMessage(imageData: Data, recipientId: String,
recipientProfile: String, recipientName: String, onSuccess:
#escaping()-> Void, onError: #escaping(_ error: String)-> Void) {
guard let senderId = Auth.auth().currentUser?.uid else {return}
guard let senderUsername = Auth.auth().currentUser?.displayName
else {return}
guard let senderProfile = Auth.auth().currentUser?.photoURL!.absoluteString else {return}
let messageId = ChatService.conversation(sender: senderId,
recipient: recipientId).document().documentID
let storageChatRef = StorageService.storagechatId(chatId: messageId)
let metadata = StorageMetadata()
metadata.contentType = "image/jpg"
StorageService.saveChatPhoto(messageId: messageId, recipientId:
recipientId, recipientProfile: recipientProfile,
recipientName: recipientName, senderProfile: senderProfile,
senderId: senderId, senderUsername: senderUsername, imageData:
imageData, metadata: metadata, storageChatRef: storageChatRef,
onSuccess: onSuccess, onError: onError)
}
func getChats(userId: String, onSuccess: #escaping([Chat])->
Void, onError: #escaping(_ error: String)-> Void, newChat:
#escaping(Chat)-> Void, listener: #escaping(_ listenerHandle:
ListenerRegistration)-> Void) {
let listenerChat = ChatService.conversation(sender:
Auth.auth().currentUser!.uid, recipient:
userId).order(by: "timestamp", descending:
false).addSnapshotListener {
(qs, err) in
guard let snapshot = qs else {
return
}
var chats = [Chat]()
snapshot.documentChanges.forEach {
(diff) in
if(diff.type == .added) {
let dict = diff.document.data()
guard let decoded = try? Chat.init(fromDictionary: dict) else {
return
}
newChat(decoded)
chats.append(decoded)
}
if(diff.type == .modified) {
print("modified")
}
if(diff.type == .removed) {
print("removed")
}
}
onSuccess(chats)
}
listener(listenerChat)
}
func getMessages(onSuccess: #escaping([Message])-> Void, onError:
#escaping(_ error: String)-> Void, newMessage: #escaping(Message)->
Void, listener: #escaping(_ listenerHandle:
ListenerRegistration)-> Void) {
let listenerMessage = ChatService.userMessages(userid:
Auth.auth().currentUser!.uid).order(by: "timestamp",
descending: true).addSnapshotListener {
(qs, err) in
guard let snapshot = qs else {
return
}
var messages = [Message]()
snapshot.documentChanges.forEach {
(diff) in
if(diff.type == .added) {
let dict = diff.document.data()
guard let decoded = try? Message.init(fromDictionary:
dict) else {
return
}
newMessage(decoded)
messages.append(decoded)
}
if(diff.type == .modified) {
print("modified")
}
if(diff.type == .removed) {
print("removed")
}
}
onSuccess(messages)
}
listener(listenerMessage)
}
}
debug showed me this line and this reference
static func conversation(sender: String, recipient: String) ->
CollectionReference {
return chats.document(sender).collection("chats").document(recipient).collection("conversation")
^Thread^
}
The guy l watch to tutoriol is dead befor the finish.and I don't fully understand my mistake.
chats/GP6sgTdilUZql2XvZUxQhQLimhm1/chats points to a collection:
collection: chats (segment 1)
document: GP6sgTdilUZql2XvZUxQhQLimhm1 (segment 2)
subcollection: chats (segment 3)
And so chats/GP6sgTdilUZql2XvZUxQhQLimhm1 points to a document. Therefore, adjust accordingly. Remember, a document must start in a collection and a document can't contain a document and a collection can't contain a collection, they must alternate.

#Published is not getting updated, State problem? - SwiftUI

Right now I have to call the function (calculatePortfolioGrossBalance) 3 times for the value to update, what am I doing wrong in the state logic?
In the code below, when I call in an init the function calculatePortfolioGrossBalance() it returns empty [], I have to call it 3 times for the value to update, However... if I print the values of getTokenBalancesModel in the line DispatchQueue.main.async { I can see the values are there, so how come in calculatePortfolioGrossBalance are not?
final class TokenBalancesClassAViewModel: ObservableObject {
#Published var getTokenBalancesModel: [TokenBalancesItemsModel] = [TokenBalancesItemsModel]()
#Published var portfolioGrossBalance: String = "0.0"
func calculatePortfolioGrossBalance() {
getTokenBalances()
DispatchQueue.main.async {
var totalBalance: Double = 0
for item in self.getTokenBalancesModel {
totalBalance += Double(item.quote!)
}
self.portfolioGrossBalance = String(format:"%.2f", totalBalance)
print(self.portfolioGrossBalance)
}
}
func getTokenBalances() {
guard let url = URL(string: "someUrlHeidiGaveMe") else {
print("Invalid URL")
return
}
print("Calling getTokenBalances() ...")
AF.request(url, method: .get).validate().responseData(completionHandler: { data in
do {
guard let data = data.data else {
print("Response Error:", data.error as Any)
return
}
let apiJsonData = try JSONDecoder().decode(TokenBalancesModel.self, from: data)
DispatchQueue.main.async {
self.getTokenBalancesModel = apiJsonData.data.items
}
} catch {
print("ERROR:", error)
}
})
}
}
you need to read up on using asynchronous functions, how to set them up and how to use them. This is important. Try something like this (untested):
final class TokenBalancesClassAViewModel: ObservableObject {
#Published var getTokenBalancesModel: [TokenBalancesItemsModel] = [TokenBalancesItemsModel]()
#Published var portfolioGrossBalance: String = "0.0"
func calculatePortfolioGrossBalance() {
getTokenBalances() { isGood in
if isGood {
var totalBalance: Double = 0
for item in self.getTokenBalancesModel {
totalBalance += Double(item.quote!)
}
self.portfolioGrossBalance = String(format:"%.2f", totalBalance)
print(self.portfolioGrossBalance)
}
}
}
func getTokenBalances(completion: #escaping (Bool) -> Void) {
guard let url = URL(string: "someUrlHeidiGaveMe") else {
print("Invalid URL")
completion(false)
return
}
print("Calling getTokenBalances() ...")
AF.request(url, method: .get).validate().responseData(completionHandler: { data in
do {
guard let data = data.data else {
print("Response Error:", data.error as Any)
completion(false)
return
}
let apiJsonData = try JSONDecoder().decode(TokenBalancesModel.self, from: data)
DispatchQueue.main.async {
self.getTokenBalancesModel = apiJsonData.data.items
completion(true)
}
} catch {
print("ERROR:", error)
completion(false)
}
})
}
}

Failed to get users- error using firebase, unable to fetch

I have been trying for some time now to create a view controller which allows you to search for and select users. I have no errors and the app builds successfully but when I go to search users in the UISearch bar I see this warning at the bottom: "Failed to get users: failedToFetch" I am not sure why it is failing. Please help.
failedToFetch appears only in my database manager swift cell. Here's the code for that--
import Foundation
import FirebaseDatabase
final class DatabaseManager {
static let shared = DatabaseManager()
private let database = Database.database().reference()
static func safeEmail(email: String) -> String {
var safeEmail = email.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "#", with: "-")
return safeEmail
}
}
extension DatabaseManager {
public func userExists(with email: String, completion: #escaping((Bool) -> Void)) {
var safeEmail = email.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "#", with: "-")
database.child(safeEmail).observeSingleEvent(of: .value, with: { snapshot in
guard ((snapshot.value as? String) != nil) else {
completion(false)
return
}
completion(true)
})
}
// inserts new user to database
public func insertUser(with user: ChatAppUser, completion: #escaping (Bool) -> Void){
database.child(user.safeEmail).setValue(["name": user.name], withCompletionBlock: { error, _ in
guard error == nil else {
print("failed to write to database")
completion(false)
return
}
self.database.child("users").observeSingleEvent(of: .value, with: { snapshot in
if var usersCollection = snapshot.value as? [[String: String]] {
//append to user dictionary
let newElement = [
"name": user.name,
"email": user.safeEmail,
]
usersCollection.append(newElement)
self.database.child("users").setValue(usersCollection, withCompletionBlock: { error, _ in
guard error == nil else{
completion(false)
return
}
completion(true)
})
}
else {
//create that array
let newCollection: [[String: String]] = [
[
"name": user.name,
"email": user.safeEmail
]
]
self.database.child("users").setValue(newCollection, withCompletionBlock: { error, _ in
guard error == nil else{
completion(false)
return
}
completion(true)
})
}
})
})
}
public func getAllUsers(completion: #escaping (Result<[[String: String]], Error>) -> Void) {
database.child("users").observeSingleEvent(of: .value, with: { snapshot in
guard let value = snapshot.value as? [[String: String]] else {
completion(.failure(DatabaseError.failedToFetch))
return
}
completion(.success(value))
})
}
public enum DatabaseError: Error {
case failedToFetch
}
}
struct ChatAppUser {
let name: String
let email: String
var safeEmail: String {
var safeEmail = email.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "#", with: "-")
return safeEmail
}
}
I know what tutorial series you are watching, and you are missing the localizedDescription portion of the enum.
public enum DatabaseError: Error {
case failedToFetch
public var localizedDescription: String {
switch self {
case .failedToFetch:
return "Database fetching failed"
}
}
}
Hopefully that helps!

How can I call a function from a Swift file and use it in a ViewController?

I have a Swift file that gets details about the user that is currently logged in/signed up named CognitoUserPoolController.swift
import Foundation
import AWSCognitoIdentityProvider
class CognitoUserPoolController {
let userPoolRegion: AWSRegionType = "Private Info"
let userPoolID = "Private Info"
let appClientID = "Private Info"
let appClientSecret = "Private Info"
var userPool:AWSCognitoIdentityUserPool?
var currentUser:AWSCognitoIdentityUser? {
get {
return userPool?.currentUser()
}
}
static let sharedInstance: CognitoUserPoolController = CognitoUserPoolController()
private init() {
let serviceConfiguration = AWSServiceConfiguration(region: userPoolRegion, credentialsProvider: nil)
let poolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: appClientID,
clientSecret: appClientSecret,
poolId: userPoolID)
AWSCognitoIdentityUserPool.register(with: serviceConfiguration,
userPoolConfiguration: poolConfiguration,
forKey:"AWSChat")
userPool = AWSCognitoIdentityUserPool(forKey: "AWSChat")
AWSDDLog.sharedInstance.logLevel = .verbose
}
func login(username: String, password:String, completion:#escaping (Error?)->Void) {
let user = self.userPool?.getUser(username)
let task = user?.getSession(username, password: password, validationData:nil)
task?.continueWith(block: { (task: AWSTask<AWSCognitoIdentityUserSession>) -> Any? in
if let error = task.error {
completion(error)
return nil
}
completion(nil)
return nil
})
}
func signup(username: String, password:String, emailAddress:String, completion:#escaping (Error?, AWSCognitoIdentityUser?)->Void) {
var attributes = [AWSCognitoIdentityUserAttributeType]()
let emailAttribute = AWSCognitoIdentityUserAttributeType(name: "email", value: emailAddress)
attributes.append(emailAttribute)
print(emailAttribute.value!)
let task = self.userPool?.signUp(username, password: password, userAttributes: attributes, validationData: nil)
task?.continueWith(block: {(task: AWSTask<AWSCognitoIdentityUserPoolSignUpResponse>) -> Any? in
if let error = task.error {
completion(error, nil)
return nil
}
guard let result = task.result else {
let error = NSError(domain: "Private Info",
code: 100,
userInfo: ["__type":"Unknown Error", "message":"Cognito user pool error."])
completion(error, nil)
return nil
}
completion(nil, result.user)
return nil
})
}
func confirmSignup(user: AWSCognitoIdentityUser, confirmationCode:String, completion:#escaping (Error?)->Void) {
let task = user.confirmSignUp(confirmationCode)
task.continueWith { (task: AWSTask<AWSCognitoIdentityUserConfirmSignUpResponse>) -> Any? in
if let error = task.error {
completion(error)
return nil
}
completion(nil)
return nil
}
}
func resendConfirmationCode(user: AWSCognitoIdentityUser, completion:#escaping (Error?)->Void) {
let task = user.resendConfirmationCode()
task.continueWith { (task: AWSTask<AWSCognitoIdentityUserResendConfirmationCodeResponse>) -> Any? in
if let error = task.error {
completion(error)
return nil
}
completion(nil)
return nil
}
}
func getUserDetails(user: AWSCognitoIdentityUser, completion:#escaping (Error?, AWSCognitoIdentityUserGetDetailsResponse?)->Void) {
let task = user.getDetails()
task.continueWith(block: { (task: AWSTask<AWSCognitoIdentityUserGetDetailsResponse>) -> Any? in
if let error = task.error {
completion(error, nil)
return nil
}
guard let result = task.result else {
let error = NSError(domain: "Private Info",
code: 100,
userInfo: ["__type":"Unknown Error", "message":"Cognito user pool error."])
completion(error, nil)
return nil
}
completion(nil, result)
return nil
})
}
}
After a user successfully signs up they are presented with HomeViewController. In HomeViewController I try to print an attribute email value like this but it does not work
import UIKit
import AWSCognitoIdentityProvider
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let userpoolController = CognitoUserPoolController.sharedInstance
userpoolController.getUserDetails(user: userpoolController.currentUser!) { (error: Error?, details:AWSCognitoIdentityUserGetDetailsResponse?) in
view.backgroundColor = .green // This line of code works, but below this line it does not.
if let loggedInUserAttributes = details?.userAttributes {
self.view.backgroundColor = .systemPink
for attribute in loggedInUserAttributes {
if attribute.name?.compare("email") == .orderedSame {
print ("Email address of logged-in user is \(attribute.value!)")
}
}
}
}
}
}
The background color successfully changes to green but does not change to pink (That was to see if the code was working.) Inside of the if let statement is where the code is not working and there are not any errors. How can I properly fix this?

Update two fields at once with updateData

I am changing my online status with this code:
static func online(for uid: String, status: Bool, success: #escaping (Bool) -> Void) {
//True == Online, False == Offline
let db = Firestore.firestore()
let lastTime = Date().timeIntervalSince1970
let onlineStatus = ["onlineStatus" : status]
let lastTimeOnline = ["lastTimeOnline" : lastTime]
let ref = db.collection("users").document(uid)
ref.updateData(lastTimeOnline) {(error) in
if let error = error {
assertionFailure(error.localizedDescription)
success(false)
}
success(true)
}
ref.updateData(onlineStatus) {(error) in
if let error = error {
assertionFailure(error.localizedDescription)
success(false)
}
success(true)
}
}
I update the lastTimeOnline and the onlineStatus.
I listen to this updates via:
// Get the user online offline status
func getUserOnlineStatus(completion: #escaping (Dictionary<String, Any>) -> Void) {
let db = Firestore.firestore()
db.collection("users").addSnapshotListener { (querySnapshot, error) in
guard let snapshot = querySnapshot else {
print("Error fetching snapshots: \(error!)")
return
}
snapshot.documentChanges.forEach { diff in
if (diff.type == .modified) {
//GETS CALLED TWICE BUT I ONLY WANT ONCE
print("modified called..")
guard let onlineStatus = diff.document.get("onlineStatus") as? Bool else {return}
guard let userId = diff.document.get("uid") as? String else {return}
var userIsOnline = Dictionary<String, Any>()
userIsOnline[userId] = [onlineStatus, "huhu"]
completion(userIsOnline)
}
}
}
}
The problem is now, since I use ref.updateData twice, my SnapshotListener .modified returns the desired data twice.
How can I update two fields in a single call, so my .modified just return one snapshot?
You can try to combine them
let all:[String:Any] = ["onlineStatus" : status ,"lastTimeOnline" : lastTime]
let ref = db.collection("users").document(uid)
ref.updateData(all) {(error) in
if let error = error {
assertionFailure(error.localizedDescription)
success(false)
}
success(true)
}