RealmSwift currentUser cannot be called if more that one valid, logged-in user exists - swift

I have a realm platform and I can register and login a user fine. When I try to open a Synced Realm file with the current User it will not allow it and Xcode throws the error currentUser cannot be called if more that one valid, logged-in user exists. I have followed all the information I can find on realms docs and I can't make sense as to why this is happening. I have a Login View Controller and a separate View Controller that contains the realm file. Here is example code of the problem I am dealing with.
LogInViewController
import Cocoa
import RealmSwift
class LoginViewController: NSViewController {
#IBOutlet weak var username: NSTextField!
#IBOutlet weak var password: NSSecureTextField!
let realm = try! Realm()
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func loginButtonPressed(_ sender: NSButton) {
let login = SyncCredentials.usernamePassword(username: "\(username.stringValue)", password: "\(password.stringValue)", register: false)
SyncUser.logIn(with: login, server: Constants.AUTH_URL, onCompletion: { [weak self] (user, err) in
if let _ = user {
if let mainWC = self?.view.window?.windowController as? MainWindowController {
mainWC.segueToHome()
print("Login Pressed")
}
} else if let error = err {
fatalError(error.localizedDescription)
}
})
}
}
SecondViewController
import Cocoa
import RealmSwift
class ViewController: NSViewController {
#IBOutlet weak var textField: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
let config = SyncUser.current!.configuration(realmURL: Constants.REALM_URL, fullSynchronization: false, enableSSLValidation: true, urlPrefix: nil)
self.realm = try! Realm(configuration: config)
}
func save(data: Data) {
do {
try realm.write {
realm.add(data)
}
} catch {
print("there was an error saving data \(error)")
}
}
#IBAction func saveData(_ sender: NSButton) {
let saveData = Data()
saveData.textField = textField.stringValue
save(data: data)
}
func loadData() {
data = realm.objects(Data.self).sorted(byKeyPath: "timestamp", ascending: false)
}
}

Maybe, this page help you solve the problem.
I solved the same problem.
///
/// quit all other users session
///
for u in SyncUser.all {
u.value.logOut()
}
///
///
///
let creds: SyncCredentials = SyncCredentials.usernamePassword(
username: YOUR_USER,
password: YOUR_PASS
)
SyncUser.logIn(
with: creds,
server: YOUR_AUTH_URL
) { (user: SyncUser?, err: Error?) in
///
/// Your action ...
///
}
After logOut and logIn, this method will success probably.
let config = SyncUser.current!.configuration(realmURL: Constants.REALM_URL, fullSynchronization: false, enableSSLValidation: true, urlPrefix: nil)
self.realm = try! Realm(configuration: config)

If you are using Realm with Firebase, a snippet like this will save you from authentication headaches.
Check to see if the SyncUser uid matches the uid from firebase, and sign out extraneous accounts.
for syncUser in SyncUser.all {
if(syncUser.key != (FirebaseAuth.Auth.auth().currentUser?.uid ?? "")) {
syncUser.value.logOut()
}
}

Related

How do I access the variables that google provides outside of the function?

i'm trying to access the emailAddress variable in a different view controller however its always not in scope.
i want to call something like
login.emailAddress
in a different vc.
heres my code for your refeerence, i understand that there are similar questions however i struggle to translate that into my code. .
import UIKit
import GoogleSignIn
let login = LoginController()
class LoginController: UIViewController {
#IBOutlet weak var signInButton: GIDSignInButton!
let signInConfig = GIDConfiguration(clientID: "12345-abcdef.apps.googleusercontent.com")
#IBAction func signIn(_ sender: Any) {
GIDSignIn.sharedInstance.signIn(with: signInConfig, presenting: self) { user, error in
guard error == nil else { return }
guard let user = user else { return }
var emailAddress = user.profile?.email
var fullName = user.profile?.name
var givenName = user.profile?.givenName
var familyName = user.profile?.familyName
var profilePicUrl = user.profile?.imageURL(withDimension: 320)
let userProfile = (fullName, givenName, emailAddress, profilePicUrl)
print("Sign in Sucessfull")
print(fullName!)
print(givenName!)
print(familyName!)
print(emailAddress!)
print(profilePicUrl!)
// If sign in succeeded, display the app's main content View.
let vc = self.storyboard?.instantiateViewController(withIdentifier: "NavigationViewController") as! UINavigationController
self.navigationController?.pushViewController(vc, animated: true)
self.present(vc, animated: true, completion: nil)
}
}
}
An option would be storing the value in a class property:
class LoginController: UIViewController {
#IBOutlet weak var signInButton: GIDSignInButton!
private var userMail: String?
let signInConfig = GIDConfiguration(clientID: "12345-abcdef.apps.googleusercontent.com")
#IBAction func signIn(_ sender: Any) {
GIDSignIn.sharedInstance.signIn(with: signInConfig, presenting: self) { user, error in
guard error == nil else { return }
guard let user = user else { return }
self.userMail = user.profile?.email
[...]
}
}
}

didInititate method for Spotify IOS SDK is not calling even though called sessionManager.initiateSession()

I'm going through Spotify's authentication process and am requesting the scopes appRemoteControl for my app to control music and userReadCurrentlyPlaying for current song. I set up everything from the SPTConfiguration, SPTSessionManager, and SPTAppRemote, and their required delegate methods (SPTAppRemoteDelegate, SPTSessionManagerDelegate, SPTAppRemotePlayerStateDelegate) as well as initiating a session with the requested scopes whenever the user presses a button but I can't get the method
func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
appRemote.connectionParameters.accessToken = session.accessToken
appRemote.connect()
print(session.accessToken)
}
to trigger. The authentication process fully works as it goes into my spotify app and returns back to my application and plays a song from the configuration.playURI = "" , however, the method above never is called. I followed the spotify demo project but still does not work. Here is my full code
class LogInViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
let spotifyClientID = Constants.clientID
let spotifyRedirectURL = Constants.redirectURI
let tokenSwap = "https://***********.glitch.me/api/token"
let refresh = "https://***********.glitch.me/api/refresh_token"
lazy var configuration: SPTConfiguration = {
let configuration = SPTConfiguration(clientID: spotifyClientID, redirectURL: URL(string: "Lyrically://callback")!)
return configuration
}()
lazy var sessionManager: SPTSessionManager = {
let manager = SPTSessionManager(configuration: configuration, delegate: self)
if let tokenSwapURL = URL(string: tokenSwap), let tokenRefreshURL = URL(string: refresh) {
self.configuration.tokenSwapURL = tokenSwapURL
self.configuration.tokenRefreshURL = tokenRefreshURL
self.configuration.playURI = ""
}
return manager
}()
lazy var appRemote: SPTAppRemote = {
let appRemote = SPTAppRemote(configuration: configuration, logLevel: .debug)
appRemote.delegate = self
return appRemote
}()
#IBAction func logIn(_ sender: UIButton) {
let requestedScopes: SPTScope = [.appRemoteControl, .userReadCurrentlyPlaying]
sessionManager.initiateSession(with: requestedScopes, options: .default)
}
}
extension LogInViewController: SPTAppRemotePlayerStateDelegate {
func playerStateDidChange(_ playerState: SPTAppRemotePlayerState) {
print("state changed")
}
}
extension LogInViewController: SPTAppRemoteDelegate {
func appRemoteDidEstablishConnection(_ appRemote: SPTAppRemote) {
print("connected")
appRemote.playerAPI?.delegate = self
appRemote.playerAPI?.subscribe(toPlayerState: { (success, error) in
if let error = error {
print("Error subscribing to player state:" + error.localizedDescription)
}
})
}
func appRemote(_ appRemote: SPTAppRemote, didFailConnectionAttemptWithError error: Error?) {
print("failed")
}
func appRemote(_ appRemote: SPTAppRemote, didDisconnectWithError error: Error?) {
print("disconnected")
}
}
extension LogInViewController: SPTSessionManagerDelegate {
func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
appRemote.connectionParameters.accessToken = session.accessToken
appRemote.connect()
print(session.accessToken)
}
func sessionManager(manager: SPTSessionManager, didFailWith error: Error) {
print("failed",error)
}
}
Figured it out. Had to get a hold of the sessionManager from the LogInViewController by making an instance of it
lazy var logInVC = LogInViewController()
then added this line of code into the openURLContexts method in scene delegate
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
print("Opened url")
guard let url = URLContexts.first?.url else {
return
}
logInVC.sessionManager.application(UIApplication.shared, open: url, options: [:])
}

Automatically delete data from Firebase Database

I have seen some other questions asked but I am having trouble getting it to work. I have a Mac app coded in swift and it has a Firebase login but the user types a key in that is stored on Firebase, is there a way to automatically delete that key when the user has successfully used it?
This is my database.
This is the code that is used currently.
import Cocoa
import FirebaseAuth
import FirebaseDatabase
class LoginViewController: NSViewController {
#IBOutlet weak var textUsername: NSTextField!
#IBOutlet weak var textPassword: NSSecureTextFieldCell!
#IBOutlet weak var btnLogin: NSButton!
var keyArray = \[Int64\]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear() {
}
func getLoginState() -> Bool{
let state = UserDefaults.standard.bool(forKey: "isRegistered")
if (state) {
return true
} else {
return false
}
}
override func viewDidAppear() {
let state = self.getLoginState()
if (state){
self.performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "loginsegue"), sender: nil)
self.view.window?.close()
}
var ref: DatabaseReference!
ref = Database.database().reference()
let keyRef = ref.child("key1")
keyRef.observe(DataEventType.childAdded, with: { (snapshot) in
// let postDict = snapshot.value as? \[String : AnyObject\] ?? \[:\]
let keyStr = snapshot.value as? Int64
if let actualPost = keyStr{
self.keyArray.append(actualPost)
}
})
}
#IBAction override func dismissViewController(_ viewController: NSViewController) {
dismiss(self)
}
#IBAction func close(sender: AnyObject) {
self.view.window?.close()
}
#IBAction func onSignup(_ sender: Any) {
// self.performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "gotosignup"), sender: sender)
// self.view.window?.close()
}
func dialogOK(question: String, text: String) -> Void {
let alert: NSAlert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = NSAlert.Style.warning
alert.addButton(withTitle: "OK")
alert.runModal()
}
#IBAction func onLogin(_ sender: Any) {
//self.btnLogin.isEnabled = false
var isKey = false
if (!self.textUsername.stringValue.isEmpty) {
for key in keyArray{
if(Int64(self.textUsername.stringValue)! == key)
{
UserDefaults.standard.set(true, forKey:"isRegistered")
self.performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "loginsegue"), sender: nil)
self.view.window?.close()
isKey = true
}
}
if (!isKey){
self.dialogOK(question: "Error", text: "Invalid Key")
}
} else {
self.dialogOK(question: "Error", text: "Please Input Key")
}
}
}
You can't sort your database like that and expect a working code, even if there's any. It will make a messy code:
You need to:
Sort your database like [1220:0]. the key first. 0 & 1 as an indicator if it's used or not.
Once the user taps onLogin() you need to set the used key value to 1
Setup Cloud Functions to check if the used key is equal to 1, if yes. then remove the key.
Do the rest of the work.
Related Articles to get you started:
Extend Realtime Database with Cloud Functions
functions.database.RefBuilder

Value of type '[Users]' has no member 'username'

I'm trying to create a simple user login ViewController that connects to a database full of user information for my app but I get the error stated in the title.
import UIKit
import Alamofire
class Users: Decodable {
let username: String
let email: String
let password: String
init(username: String, email: String, password: String) {
self.username = username
self.email = email
self.password = password
}
class LoginVC: UIViewController {
var loggingin = [Users]()
#IBOutlet weak var usernameTxtField: UITextField!
#IBOutlet weak var passwordTxtField: UITextField!
#IBOutlet weak var checkCredsBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let jsonURL = "http://host-2:8888/getLogin.php"
let url = URL(string: jsonURL)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
do {
self.loggingin = try JSONDecoder().decode([Users].self, from: data!)
for eachUser in self.loggingin {
print(eachUser.username + " : " + eachUser.password)
}
}
catch {
print("Error")
}
}.resume()
}
#IBAction func checkCreds(_ sender: Any) {
if usernameTxtField == loggingin.username && passwordTxtField == loggingin.password {
print("YES")
}
}
}
}
The reason of this compile time error appears in checkCreds function, you are trying to access the username and password properties directly from the array which is obviously incorrect. What you should do instead is to get the desired object from loggingin array and do comparing with its properties:
#IBAction func checkCreds(_ sender: Any) {
let currentUser = loggingin[0]
if usernameTxtField == currentUser.username && passwordTxtField == currentUser.password {
print("YES")
}
}
In the above example, I just got the first object; I would assume that you already able to get the desired object currentUser (what's the used index) for getting the object from the loggingin.

Custom FirebaseUI AuthViewController

Using the FirebaseUI Auth 1.0 version and swift 3.
Followed the sample and read the explains how to subclass the FUIAuthPickerViewController but everything I tried it's giving me a
fatal error: unexpectedly found nil while unwrapping an Optional valueonlet controller = self.authUI!.authViewController()
I exactly copied the example and there is it working, so can someone explain what I did wrong or why this is happening?
Code in my ViewController where I want the user to login
ViewController.swift
import Firebase
import FirebaseAuthUI
import FirebaseGoogleAuthUI
import FirebaseFacebookAuthUI
var ref: FIRDatabaseReference!
var remoteConfig: FIRRemoteConfig!
fileprivate var _refHandle: FIRDatabaseHandle!
fileprivate var _authHandle: FIRAuthStateDidChangeListenerHandle!
fileprivate(set) var auth: FIRAuth? = FIRAuth.auth()
fileprivate(set) var authUI: FUIAuth? = FUIAuth.defaultAuthUI()
fileprivate(set) var customAuthUIDelegate: FUIAuthDelegate = FUICustomAuthDelegate()
func configAuth() {
//listen for changes in auth state
_authHandle = FIRAuth.auth()?.addStateDidChangeListener({ (auth: FIRAuth, currentuser: FIRUser?) in
self.users.removeAll(keepingCapacity: false)
self.tableView.reloadData()
if currentuser != nil {
// User is signed in.
self.fetchUser()
} else {
// No user is signed in.
//self.login()
self.loginSession()
}
})
}
func loginSession() {
self.authUI?.delegate = self.customAuthUIDelegate
let googleAuth = FUIGoogleAuth(scopes: [kGoogleUserInfoEmailScope,
kGooglePlusMeScope,
kGoogleUserInfoProfileScope])
let facebookAuth = FUIFacebookAuth(permissions: ["public_profile",
"email",
"user_friends"])
self.authUI?.providers = [googleAuth, facebookAuth]
let controller = self.authUI!.authViewController()
self.present(controller, animated: true, completion: nil)
}
Here the
FUICustomAuthDelegate.swift
import UIKit
import FirebaseAuthUI
import FirebaseAuth
class FUICustomAuthDelegate: NSObject, FUIAuthDelegate {
func authUI(_ authUI: FUIAuth, didSignInWith user: FIRUser?, error: Error?) {
guard let authError = error else { return }
let errorCode = UInt((authError as NSError).code)
switch errorCode {
case FUIAuthErrorCode.userCancelledSignIn.rawValue:
print("User cancelled sign-in");
break
default:
let detailedError = (authError as NSError).userInfo[NSUnderlyingErrorKey] ?? authError
print("Login error: \((detailedError as! NSError).localizedDescription)");
}
}
func authPickerViewController(forAuthUI authUI: FUIAuth) -> FUIAuthPickerViewController {
return FUICustomAuthPickerViewController(authUI: authUI)
}
and the
FUICustomAuthPickerViewController.swift
import FirebaseAuthUI
#objc(FUICustomAuthPickerViewController)
class FUICustomAuthPickerViewController: FUIAuthPickerViewController {
#IBAction func onClose(_ sender: AnyObject) {
self.cancelAuthorization()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}