Can someone explain what "extra trailing closure passed in call" means? - swift

I'm receiving the error "Extra trailing closure passed in call" on the authViewModel.fetchUser() function. From what I've gathered researching online this means that fetchuser can't have the trailing closure (the brackets), I am confused about what in my fetchuser function says that it cannot have the {} after the call. Or maybe I'm not understanding the error at all. Thank you in advance!
FeedCellViewModel
import Foundation
class FeedCellViewModel: ObservableObject {
#Published var posts = [Post]()
let service = PostService()
let authViewModel = AuthViewModel()
init() {
fetchPosts()
}
func fetchPosts() {
service.fetchPosts { posts in
self.posts = posts
for i in 0 ..< posts.count {
let uid = posts[i].uid
self.authViewModel.fetchUser() { user in
self.posts[i].user = user
}
}
}
}
}
AuthViewModel
import SwiftUI
import FirebaseAuth
import FirebaseCore
import FirebaseStorage
import FirebaseFirestore
import FirebaseFirestoreSwift
class AuthViewModel: NSObject, ObservableObject {
#Published var userSession: FirebaseAuth.User?
#Published var currentUser: User?
#Published var selectedImage: UIImage?
#Published var didAuthenticateUser = false
private var tempUserSession: FirebaseAuth.User?
private let service = UserService()
static let shared = AuthViewModel()
override init() {
super.init()
userSession = Auth.auth().currentUser
fetchUser()
}
func login(withEmail email: String, password: String) {
Auth.auth().signIn(withEmail: email, password: password) { result, error in
if let error = error {
print("DEBUG: Failed to sign in with error \(error.localizedDescription)")
return
}
self.userSession = result?.user
self.fetchUser()
}
}
func register(withEmail email: String, password: String, fullname: String) {
Auth.auth().createUser(withEmail: email, password: password) { result, error in
if let error = error {
print("DEBUG: Failed to register with error \(error.localizedDescription)")
return
}
guard let user = result?.user else { return }
self.tempUserSession = user
let data = ["email": email,
"fullname": fullname,
"uid": user.uid]
COLLECTION_USERS
.document(user.uid)
.setData(data) { _ in
self.didAuthenticateUser = true
}
self.uploadProfileImage(self.selectedImage)
self.fetchUser()
}
}
func signOut() {
// sets user session to nil so we show login view
self.userSession = nil
// signs user out on server
try? Auth.auth().signOut()
}
func uploadProfileImage(_ image: UIImage?) {
guard let uid = tempUserSession?.uid else { return }
ImageUploader.uploadImage(image: image) { profileImageUrl in
Firestore.firestore().collection("users")
.document(uid)
.updateData(["profileImageUrl": profileImageUrl]) { _ in
self.userSession = self.tempUserSession
}
}
}
func fetchUser() {
guard let uid = userSession?.uid else { return }
COLLECTION_USERS.document(uid).getDocument { snapshot, _ in
guard let user = try? snapshot?.data(as: User.self) else { return }
self.currentUser = user
}
}
}

You're seeing this error because your fetchUser() function doesn't take a closure parameter (or any parameters for that matter).
A trailing closure is just a nicer way of passing a closure as a parameter, given it's the last parameter to a method.
Try running this example in a playground to get a feel for this:
func hello(closure: () -> Void) {
print("calling closure")
closure()
print("finished")
}
// these are the same
hello(closure: { print("hello!!") })
hello { print("hello!!") }
If you want to provide the user in a closure to the caller, return the user as a parameter to the closure in addition to setting the currentUser.
func fetchUser(finishedFetching: #escaping (User) -> Void) {
guard let uid = userSession?.uid else { return }
COLLECTION_USERS.document(uid).getDocument { snapshot, _ in
guard let user = try? snapshot?.data(as: User.self) else { return }
self.currentUser = user
finishedFetching(user)
}
}
Read more about closures in the Swift language guide.
They are essentially unnamed functions that you can store and pass around.
You'll learn there why I marked our closure as #escaping.

Related

How to check if a user already exists in a Firestore collection after signing in with Firebase Auth in SwiftUI

#Published var isNewUser: Bool?
init() {
self.isNewUser = false
}
func checkIfTheUserExistsInDataBase(
userID: String?, completion: #escaping (_ isNewuser: Bool) -> Void
) {
let docRef = db.collection("users").whereField("user_id", isEqualTo: userID!).limit(to: 1)
docRef.getDocuments { querySnapshot, error in
if error != nil {
print(error?.localizedDescription)
} else {
if let doc = querySnapshot?.documents, doc.isEmpty {
completion(true)
} else {
completion(false)
}
}
}
}
func login(
email: String, password: String,
completion: #escaping (_ error: Error?, _ isEmailVerified: Bool) -> Void
) {
Auth.auth().signIn(withEmail: email, password: password) { authDataResult, error in
if error == nil {
if authDataResult!.user.isEmailVerified {
DispatchQueue.main.async {
self.checkIfTheUserExistsInDataBase(userID: authDataResult?.user.uid) { isNewUser in
self.isNewUser = isNewUser
}
}
UserDefaults.standard.set(authDataResult?.user.uid, forKey: CurrentUserDefaults.userID)
completion(error, true)
} else {
print("Email not verified")
completion(error, false)
}
} else {
completion(error, false)
}
}
}
I tried to use DispatchSemaphore to let a longer running function execute first which is checkIfTheUserExistsInDataBase, but it froze my app. Is there a better way to do this?
Firebase supports async/await (see this short, this video, and this blog post I created to explain this in detail.
To answer your question: you should use async/await to call signing in the user, waiting for the result, checking if the user exists in your Firestore collection, and the updating the UI.
The following code snippet (which is based on this sample app) uses the new COUNT feature in Firestore to count the number of documents in the users collection to determine if there is at least one user with the ID of the user that has just signed in.
func isNewUser(_ user: User) async -> Bool {
let userId = user.uid
let db = Firestore.firestore()
let collection = db.collection("users")
let query = collection.whereField("userId", isEqualTo: userId)
let countQuery = query.count
do {
let snapshot = try await countQuery.getAggregation(source: .server)
return snapshot.count.intValue >= 0
}
catch {
print(error)
return false
}
}
func signInWithEmailPassword() async -> Bool {
authenticationState = .authenticating
do {
let authResult = try await Auth.auth().signIn(withEmail: self.email, password: self.password)
if await isNewUser(authResult.user) {
}
return true
}
catch {
print(error)
errorMessage = error.localizedDescription
authenticationState = .unauthenticated
return false
}
}
See this video for more details about how to implement Firebase Authentication in SwiftUI apps.

Firebase sign in not working after I sign out

So the first sign in into the Swift UI app works fine. I sign in and the view changes to the home view from the sign in view. However, after I log out, the sign in doesn't cause my view to change, so I assume it doesn't work.
Here is my AuthViewModel where I handle the sign in and sign out.
import FirebaseAuth
class AuthViewModel: ObservableObject {
static let shared = AuthViewModel()
private(set) var authSubscription: AuthStateDidChangeListenerHandle?
#Published var currentUser: User?
#Published var error: Error?
init() {
authSubscription = Auth.auth().addStateDidChangeListener { [weak self] (auth, user) in
self?.currentUser = user
}
}
func signIn(email: String, password: String) {
Auth.auth().signIn(withEmail: email, password: password) { [weak self] (authResult, error) in
if let error = error {
self?.error = error
} else {
self?.error = nil
}
}
}
func signUp(email: String, password: String) {
Auth.auth().createUser(withEmail: email, password: password) { [weak self] (authResult, error) in
if let error = error {
self?.error = error
} else {
self?.error = nil
}
}
}
func signOut() {
do {
try Auth.auth().signOut()
} catch let error {
self.error = error
}
}
}
Also here is how I am switching from my sign up view to the home view
struct ContentView: View {
#State var screenOn = 0
#EnvironmentObject var authViewModel: AuthViewModel
var body: some View {
if let user = authViewModel.currentUser {
if screenOn == 0 {
someView(screenOn: $screenOn)
.onAppear(perform: UIApplication.shared.addTapGestureRecognizer)
.onOpenURL { url in
let link = url.absoluteString
}
} else if screenOn == 1 {
someView(screenOn: $screenOn)
.onAppear {
authViewModel.signOut()
}
} else if screenOn == 3 {
someView(screenOn: $screenOn)
} else if screenOn == 4 {
someView(screenOn: $screenOn)
}
} else {
Loginpage()
}
}
}

Update data stored in Firebase using MVVM nested models

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)))
})
}
}
}
}

Why is my swift code executing out of order? Firebase authentication

I am calling Authenticator.loginUser() with the expectation that the method will log in a user then call getCurrentUser(). Based on printed output, getCurrentUser() is executing first. Is there a way to force it to execute in order?
class Authenticator: ObservableObject {
#Published var currentUser: UserProfile = UserProfile()
#Published var user: String = ""
#Published var documentId: String = ""
func loginUser (email: String, password: String, viewModel: UsersViewModel) {
FirebaseAuth.Auth.auth().signIn(withEmail: email, password: password, completion: { result, error in
guard error == nil else {
print ("error: \(error!)")
return
}
print ("user signed in")
})
self.user = self.getCurrentUser(viewModel: viewModel)
}
func getCurrentUser(viewModel: UsersViewModel) -> String {
guard let userID = Auth.auth().currentUser?.uid else {
return ""
}
viewModel.users.forEach { i in
if (i.userId == userID) {
currentUser = i
}
}
documentId = currentUser.documentId!
print("auth.documentId \(documentId)")
return userID
}
}
FirebaseAuth.Auth.auth().signIn is asynchronous - it runs in the background and not on the main thread. This means that signIn will be called some time in the future.
A solution is to put the call to getCurrentUser in the completion block:
func loginUser(email: String, password: String, viewModel: UsersViewModel) {
FirebaseAuth.Auth.auth().signIn(withEmail: email, password: password, completion: { result, error in
guard error == nil else {
print("error: \(error!)")
return
}
print("user signed in")
self.user = self.getCurrentUser(viewModel: viewModel) // move here
})
}

Cannot convert value of type `AuthResultCallback`?

I know about other similar questions, but they are to do with Auth.auth().signIn and signUp respectively, where there is a completion handler argument present within the function.
I'm trying to include a sign in the anonymous function to my SessionStore class so that my app observes the state of the user, i.e., whether he is signed in (anonymously or otherwise) or signed out, and accordingly display the relevant view.
However, when trying to add anonymous sign up to my SessionStore class, I get the following error:
Cannot convert value of type 'AuthResultCallback' (aka '(Optional<User>, Optional<Error>) -> ()') to expected argument type 'AuthDataResultCallback?' (aka 'Optional<(Optional<AuthDataResult>, Optional<Error>) -> ()>')
My code is as follows:
class SessionStore: ObservableObject {
var didChange = PassthroughSubject<SessionStore, Never>()
#Published var session: User? {didSet {self.didChange.send(self)}}
var handle: AuthStateDidChangeListenerHandle?
func listen() {
handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
if let user = user {
self.session = User(uid: user.uid, email: user.email)
} else {
self.session = nil
}
})
}
func signUp(email: String, password: String, handler: #escaping AuthDataResultCallback) {
Auth.auth().createUser(withEmail: email, password: password, completion: handler)
}
func signIn(email: String, password: String, handler: #escaping AuthDataResultCallback) {
Auth.auth().signIn(withEmail: email, password: password, completion: handler)
}
func signOut() {
do {
try Auth.auth().signOut()
self.session = nil
} catch {
print("Error signing user out")
}
}
func signUpAnonymously(handler: #escaping AuthResultCallback) {
Auth.auth().signInAnonymously(completion: handler) // **ERROR APPEARS HERE**
}
func unbind() {
if let handle = handle {
Auth.auth().removeStateDidChangeListener(handle)
}
}
deinit {
unbind()
}
}
struct User {
var uid: String
var email: String?
init(uid: String, email: String?) {
self.uid = uid
self.email = email
}
}
Can someone tell me how to fix this error?
The code snippet you pasted is from an outdated tutorial. As of Xcode 11 beta 5, you no longer need to use PassthroughSubject to send notifications about property changes. Sarun's blog post has a great and concise section on what has changed, I encourage you to read it.
Please also note that you don't need to define your own User class if you only care about the user's ID and their email address, as these attributes are already defined on Firebase's own User type (by way of implementing the UserInfo protocol).
Here is a snippet that shows how to implement the callback you're interested in (see registerStateListener).
class AuthenticationService: ObservableObject {
#Published var user: User?
private var handle: AuthStateDidChangeListenerHandle?
init() {
registerStateListener()
}
func signIn() {
if Auth.auth().currentUser == nil {
Auth.auth().signInAnonymously()
}
}
func signOut() {
do {
try Auth.auth().signOut()
}
catch {
print("Error when trying to sign out: \(error.localizedDescription)")
}
}
func updateDisplayName(displayName: String, completionHandler: #escaping (Result<User, Error>) -> Void) {
if let user = Auth.auth().currentUser {
let changeRequest = user.createProfileChangeRequest()
changeRequest.displayName = displayName
changeRequest.commitChanges { error in
if let error = error {
completionHandler(.failure(error))
}
else {
if let updatedUser = Auth.auth().currentUser {
print("Successfully updated display name for user [\(user.uid)] to [\(updatedUser.displayName ?? "(empty)")]")
// force update the local user to trigger the publisher
self.user = updatedUser
completionHandler(.success(updatedUser))
}
}
}
}
}
private func registerStateListener() {
if let handle = handle {
Auth.auth().removeStateDidChangeListener(handle)
}
self.handle = Auth.auth().addStateDidChangeListener { (auth, user) in
print("Sign in state has changed.")
self.user = user
if let user = user {
let anonymous = user.isAnonymous ? "anonymously " : ""
print("User signed in \(anonymous)with user ID \(user.uid). Email: \(user.email ?? "(empty)"), display name: [\(user.displayName ?? "(empty)")]")
}
else {
print("User signed out.")
self.signIn()
}
}
}
}
If you're interested in more background, check out my article series about building a to-do app with SwiftUI and Firebase: part 1 (building the UI using SwiftUI), part 2 (storing data in Firestore and using Firebase Anonymous Auth), part 3 (Sign in with Apple)