Swift & Parse.com find by specific column not ID - swift

Reference: http://blog.parse.com/2014/06/06/building-apps-with-parse-and-swift/
I'm trying to find a columns value: userPassword, based in the userName column. Using the above reference from Parse it shows that to get data from parse you should use:
var query = PFQuery(className: "GameScore")
query.getObjectInBackgroundWithId(gameScore.objectId) {
(scoreAgain: PFObject!, error: NSError!) -> Void in
if !error {
NSLog("%#", scoreAgain.objectForKey("playerName") as NSString)
} else {
NSLog("%#", error)
}
}
However, as you can see it is looking for (gameScore.objectId) - The problem is I do not know this value as the user isnt entering a complex parse generated ID. They're entering their chosen username. In the rows I have userName and Password set. How do I search the rows for the userPassword so I can verify it based on their specified userName.
Thanks in advance

Why are you querying the database for a username and password. Adding a new user is very simple with Parse. Taken directly from their docs:
Query User table on Parse
You can query the user table first, using a PFQuery:
PFQuery *query = [PFUser query];
[query whereKey:#"username" equalTo:username];
Adding New User
The idea of user accounts that let people access their information and share it with others in a secure manner is at the core of any social app. Whether your app creates its own sharing environment or integrates with existing social networks, you will need to add functionality to let people manage their accounts in your app.
We provide a specialized user class called PFUser that automatically handles much of the functionality required for user account management.
First make sure to include our SDK libraries from your .h file:
#import <Parse/Parse.h>
Then add this code into your app, for example in the viewDidLoad method (or inside another method that gets called when you run your app):
func myMethod() {
var user = PFUser()
user.username = "myUsername"
user.password = "myPassword"
user.email = "email#example.com"
// other fields can be set just like with PFObject
user["phone"] = "415-392-0202"
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, error: NSError!) -> Void in
if error == nil {
// Hooray! Let them use the app now.
} else {
let errorString = error.userInfo["error"] as NSString
// Show the errorString somewhere and let the user try again.
}
}
}
This call will asynchronously create a new user in your Parse app. Before it does this, it checks to make sure that both the username and email are unique. It also securely hashes the password in the cloud.
You can learn more about Users, including how to verify emails and handle read and write permissions to data, by visiting our docs.
Run your app. A new object of the class User will be sent to the Parse Cloud and saved. When you're ready, click the button below to test if a User was created.
Further
I created a tutorial about connecting to parse if you still wish to go down the route of querying the server manually:
http://ios-blog.co.uk/tutorials/swift-create-user-sign-up-based-app-with-parse-com-using-pfuser/

Related

Why does the display name of my users keep reverting in Firebase with swift?

I encountered the following error in my swift project: https://github.com/firebase/firebase-ios-sdk/issues/4393. To overcome this issue I change the display name to the characters before the # in a users email like so:
var displayName = user.email!
if let atRange = displayName.range(of: "#") {
displayName.removeSubrange(atRange.lowerBound.. < displayName.endIndex)
}
if user.displayName!.count < 2{
let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = displayName
changeRequest?.commitChanges {(err) in
if let err = err{
print(err)
}
}
}
This works when I first log in but if I log out and then back in again the display name reverts back to Optional(""). Why would it be doing this?
Edit
I created a workaround where I run the above code not only when a user is first created, but every time a user logs in, this seems excessive though and there must be a reason why the display name keeps getting overwritten.
This is not an error, this is intended behaviour from Apple's side. By default, you should be updating the Firebase user with the appropriate display name rather than relying on 3rd party information since these are only available on first login.
Simply checking if the name exists on initial login and is longer than 0 characters, not null, etc. then you can update the name with the following:
let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = displayName
changeRequest?.commitChanges { (error) in
// ...
}
This is also documented within the git-issue you posted https://github.com/firebase/firebase-ios-sdk/issues/4393#issuecomment-612193703
Ultimately, you are logging into your app as a Firebase user, not an apple user. Apple is only Authenticating the process, so you must update the Firebase user where possible as Apple is highly inconsistent across all platforms.

Store new user information to Firebase with multiple view controllers

I have three different view controllers: (in this order) first+last name, birthday, email+password.
I have already connected my app to firebase and I know how to send the user information to firebase, but only for one of the view controllers. I want firebase to store all of the information from all three view controllers (name, birthday, and email/password) after clicking the "sign up" button on the last view controller (email+password). Please let me know how I can combine all of the information to one new user, rather than making them all new users.
It seems like you are making multiple API calls rather than one single API to sign up a new user, meaning only one call is necessary. There are a couple of different ways you could do this, but the main idea is that you need to get all the data to the very end of the onboarding sign up and then call the Firebase API.
I suggest you make a data object called NewUser and store the data as you progress through the sign-up process. It would look something like this:
class NewUser {
// MARK: - Variables
var userID:String
var name:String?
var birthday:String?
var email:String?
var password:String?
// MARK: - Init Variables
init(userID:String, name:String, birthday:String, email:String, password:String) {
self.userID = userID
self.name = name
self.birthday = birthday
self.email = email
self.password = password
}
}
Example to set name data:
NewUser.name = name
Then call NewUser.name to access the stored data.

How to manage acces control at login

I been looking for control what a kind of user can see in my app, this is a scholar project. I'm using Swift and Firebase Authentication. I have two kinds of users: Model and Client. In my app I have some views for the Model and other for the Client. What I want to do is that once they log in, in to the app show just the views for their kind of user. I don't know how to verify if the user that is trying to sign in is a Model or a Client.
#IBAction func signInTapped(_ sender: UIButton) {
if validateFields(){
Auth.auth().signIn(withEmail: emailTxt.text!, password: passTxt.text!, completion:{
(user, error) in
if let u = user {
//User is found
}else{
//Error
}
})
}
}
I know that the code need to be where is the comment "User is found" but I don't know if I need to modify something into the the Firebase Console
Create a Firebase Database or Firestore to your project.
Now when you authenticate a user you should also create a userobject in your databse. In this object you can create a field to store whether your user is a model or a client.
Now once the user has signed in, you can download this userobject from the database, check whether the user is a model or client, and send the user to their corresponding views.
You can use custom claims.
You set them using the Admin SDK
// Javascript
admin.auth().setCustomUserClaims(uid, {model: true}).then(() => {
// The new custom claims will propagate to the user's ID token the
// next time a new one is issued.
});
Then in client SDK just read the claim.
user.getIDTokenResult(completion: { (result, error) in
guard let model = result?.claims?["model"] as? NSNumber else {
// Something
}
if model.boolValue {
// Show something else
} else {
// Something else again
}
})
Shamelessly copied from Firebase Docs

Making public realms on Realm Object Server in Swift

I am trying to make a public realm that all users will have read permissions to. The realm team mentioned this capability in this webinar, but I am having trouble finding any documentation on how to do it.
Here is a nice image from the webinar that illustrates the types of realms that can be made in the object server. I am having trouble finding out how to make a public realm.
Here are directions for doing what you want. Be aware that this feature has changed slightly since that webinar was presented. (We also need to improve our documentation, so thank you for asking this question!)
Create an admin user. You can do this by creating a regular user, going to the web dashboard, and editing the user so that it is an administrator. If the user is an admin, upon logging in its isAdmin property should be true.
Using your admin user, open a global Realm. A global Realm is one whose path doesn't contain ~, for example /myGlobalRealm versus /~/eachUserHasTheirOwnCopy. Note that this Realm is completely inaccessible to other users by default. If the Realm doesn't yet exist, the Realm Object Server will automatically create it. This will be your public Realm.
Create an RLMSyncPermissionValue to grant read permissions to all users. This means specifying the path to your public Realm (/myGlobalRealm), as well as a user ID of *.
Then call -[RLMSyncUser applyPermission:callback:] on your admin user with your new permission value, and ensure that the server properly set the permission.
Try opening your public Realm using a different user, and make sure it works.
I hope this helps.
Swift Solution
You can run this once in your simulator to create a global realm with default read/write permissions.
SyncUser.logIn(with: .usernamePassword(username: "ADMIN USERNAME", password: "ADMIN PASSWORD!"), server: URL(string: "Your Server URL")! { (user, error) in
guard user != nil else{
print(error)
return
}
do{
let globalRealm = try Realm(configuration: Realm.Configuration(syncConfiguration: SyncConfiguration(user: user!, realmURL: URL(string: "realm://<YOUR SERVER>:9080/GlobalRealm")!), readOnly: false))
}catch{
print(error)
}
let permission = SyncPermissionValue(realmPath: "/GlobalRealm", userID: "*", accessLevel: SyncAccessLevel.write)
user!.applyPermission(permission) { error in
if let error = error{
print(error)
}else{
user!.retrievePermissions { permissions, error in
if let error = error {
print("error getting permissions")
}else{
print("SUCCESS!")
}
}
}
}
}
Here is a server function to write a public realm:
const Realm = require('realm');
const server_url = 'realm://<Your Server URL>:9080'
const realmName = 'PublicRealm'
const REALM_ADMIN_TOKEN = "YOUR REALM ADMIN TOKEN"
const adminUser = Realm.Sync.User.adminUser(REALM_ADMIN_TOKEN);
var newRealm = new Realm({
sync: {
user: adminUser,
url: server_url + '/' + realmName
},
});
Paste the code into the function editor in the realm dashboard and run the function to create a public realm. You can modify the public realm by changing the properties in the realm constructor.

Firebase wrapping user information with an "Optional()" wrapper

My code to get a current user's email address is:
let currUserId = FIRAuth.auth()?.currentUser?.email
currUser = "Logged in as User: \(currUserId)"
The result is shown like this:
Logged in as User: Optional("email")
Is there any way to eliminate this wrapper. I seem to be having this same issue when Firebase pushes my UID to my database, as it likes to wrap it in an Optional("uid") wrapper.
Unwrap the optional:
if let user = currUserID{
print(user)
}