I'm building a user registration that connects to firebase. I am unable to get firebase to discern if an email domain is valid or not so I want to provide an array of valid well known email domains which users can have to register for my app. I want to error handle for the occurence of an invalid email domain, so I need to be able to compare the end of the email the user entered with the array of valid emails I will allow. How can I check to confirm that ex: 'apples#gmail.com' is valid but ex: 'apples#gnail.com' is not valid?
let emails: Array = ["gmail.com", "yahoo.com", "comcast.net", "hotmail.com", "msn.com", "verizon.net"]
#IBAction func nextBtnPressed(_ sender: Any) {
let ref: DatabaseReference!
ref = Database.database().reference()
if let email = emailTextField.text, let pwd = passwordTextField.text, let firstName = firstNameTextField.text, let lastName = lastNameTextField.text, let dob = birthdayTextField.text {
if pwd != self.reEnterPassTextField.text {
errorMessageLbl.text = "Passwords do not match"
errorMessageLbl.isHidden = false
return
} else if firstName == "" || lastName == "" || dob == ""{
errorMessageLbl.text = "Cannot leave fields blank"
errorMessageLbl.isHidden = false
return
} else if email.characters.elementsEqual([emails]) {
print("Failure")
One of the way you can do this:
let validDomains = ["gmail.com", "yahoo.com", "comcast.net", "hotmail.com", "msn.com", "verizon.net"]
let emailTextBlockText = "example#gmail.com"
if let domain = emailTextBlockText.components(separatedBy: "#").last, validDomains.contains(domain) {
// Entered email has valid domain.
}
Related
this is supposed to take the user ID from the result!.user.uid and store it a variable or function in order for me to use it again.
the problem is that I dont know how to get it to store the value outside of this function.
Ive tried to make it store to a variable outside of the initial button function, and Ive also tried to return it outside of the function by removing a part of the code which made it become a void. Im not sure where i need to go/what else I can try and do in order to fix this problem.
If anybody know how do I retrieve my document ID from this code your help would be greaty appreciated
#IBAction func NextButtonTapped(_ sender: Any) {
//validate the fileds
let Error = validateFields()
if Error != nil {
// there is somthing wrong with the fields show error message
showError(Error!)
}
else {
// create cleaned versions of the data
let Password = PasswordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Email = EmailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Firstname = FirstnameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Lastname = LastnameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let Age = AgeTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
// create the user
Auth.auth().createUser(withEmail: Email, password: Password) { (results, Err) in
// check for errors
if Err != nil {
// there was an error creating the user
self.showError("Error creating user")
}
else {
// user was created succesfully store first and last name
let db = Firestore.firestore()
db.collection("users").document(results!.user.uid).setData(["first name":Firstname, "last name":Lastname, "age":Age, "uid":results!.user.uid]) { (Error) in
if Error != nil {
// show error message
self.showError("error saving user data")
}
//showing users document id
}
//transition to the home screen
self.transitionToHome()
}
}
}
}
I have no idea what to do any help would be amazing,
thank you very much!!!!
Define a uid variable outside of the IBAction function like so.
var uid: String? = nil
Then, within the createUser function
self.uid = results!.user.uid
What is the correct way to set CNContact.predicateForContacts to select the field "email" in CNContacts? Like in SQL where email like "%lbs%"?
This is my function to delete a lot of imported contacts I want to get rid of. But the function return 0 hits. But there are more than 1000 contacts with "lbs" in the field email.
func deleteContacts(){
let store = CNContactStore()
let predicate = CNContact.predicateForContacts(matchingName: "lbs")
let toFetch = [CNContactEmailAddressesKey]
do{
let contacts = try store.unifiedContacts(matching: predicate,keysToFetch: toFetch as [CNKeyDescriptor])
guard contacts.count > 0
else{
print("No contacts found")
return
}
guard let contact = contacts.first else{
return
}
let req = CNSaveRequest()
let mutableContact = contact.mutableCopy() as! CNMutableContact
req.delete(mutableContact)
do{
try store.execute(req)
print("Success, deleted the data: Count: \(contacts.count)")
} catch let e{
print("Error = \(e)")
}
} catch let err{
print(err)
}
}
Your predicate is trying to find contacts where the person's name matches the string lbs.
There is no built-in predicate for finding contacts that have an email address containing a specific string. The solution is to use enumerateContacts and look at each individual contact's list of email addresses. You will then need to check to see if any of the contact's email address contains the string you wish to check.
I just started working with servers in swift and I'm using parse server to store a database of users when they create an account for my app. I have this function called sign up that is linked to a sign up button which works fine and properly stores user's info into my parse database.:
#IBAction func signUp(_ sender: AnyObject) {
//I first check to see if the users left any of the fields blank
if firstName.text == "" || lastName.text == "" || email.text == "" || userName.text == "" || password.text == "" {
createAlert(title: "Error in form", message: "Please fill in all text fields")
//If everything is filled in
}else{
let user = PFUser()
user.username = userName.text
user["firstname"] = firstName.text
user["lastname"] = lastName.text
user.email = email.text
user.password = password.text
user.signUpInBackground(block: { (success, error) in
if error != nil {
var displayErrorMessage = "Please try again later."
if let errorMessage = (error! as NSError).userInfo["error"] as? String {
displayErrorMessage = errorMessage
}
self.createAlert(title: "Signup error", message: displayErrorMessage)
}else{
print("User signed up")
}
})
}
}
Can anyone help me write a function that deletes a specified user or many loops through all users and deletes them.
Thanks
Don't put that code on a client. Yuck.
Deleting a user is something you want to safeguard very carefully. Put that in cloud code if you really need it, and do validation to ensure it's used properly.
I.e., a user should only be able to make the request to delete their own user. Make a cloud code function that has the parameter userId, and check that param against request.user.id. If they don't match, return an error. Otherwise you can call the destroy method on that User.
You should also put a CLP in place to only allow the master key to delete a User object.
In a ViewController I have three text fields (mail, password, repeat password). Before sending data to the server I do a little validation (check if text exists, if mail is valid, etc.).
I do this way:
let email = emailTextfield.text
let password = passwordTextfield.text
let repeatPassword = repeatPasswordTextfield.text
if let e = email {
if let p = password {
if let rp = repeatPassword{
if(e.isEmpty || p.isEmpty || rp.isEmpty){//cut mail validation...
The question is: is this the best way to do it? Is there any better (maybe more compact) way? Thanks in advance.
Starting from Swift 2.0 or so, you no longer need to construct an optional binding pyramid of doom, but can use several bindings (as well as boolean conditionals) in the same if statment. E.g.:
if let email = emailTextfield.text, !email.isEmpty,
let password = passwordTextfield.text, !password.isEmpty,
let repeatPassword = repeatPasswordTextfield.text, !repeatPassword.isEmpty {
// proceed only for all non-nil and non-empty above ...
}
These will naturally short-circuit for first failed binding/false conditional met.
I am not sure but I can see two solutions:
-The first one is clearer:
if let e = email, let p = password, let rp = repeatPassword {
if e.isEmpty || p.isEmpty || rp.isEmpty {
// do your things
}
}
-the second one is more compact:
if email != nil, password != nil, repeatPassword != nil, (email!.isEmpty || password!.isEmpty || repeatPassword!.isEmpty) {
// do the things force unwrapping every variable
}
the second solution works because if email or password or repeatPassword is nil, the compiler won't continue reading conditions, and consequently won't crash reading for example repeatPassword!.isEmpty as nil.isEmpty
To build on #dfri 's answer, I can think of this solution (non tested) :
if let e = email, let p = password, let rp = repeatPassword, (e.isEmpty, p.isEmpty, rp.isEmpty) {
// cut mail validation
}
the last one, if works, is obviously the most elegant solution and I'll delete it as soon as #dfri updates his solution to comply with your answer :)
if let email = emailTextfield.text where !email.isEmpty,
let password = passwordTextfield.text where !password.isEmpty,
let repeatPassword = repeatPasswordTextfield.text where !repeatPassword.isEmpty {
// Go for it.
}
You can just do
if email?.isEmpty || password?.isEmpty || repeatPassword?.isEmpty { //break }
Don't worry about nil value, let it as optionnal and everything will be fine.
I am working on new Firebase Log in. There are two categories in database. "Cooks" and "Customer". "Cooks" has a CookViewController and "Customers" has a customerViewController. I need to know which category this email belongs to so after logging in, segue to CookViewController or CustomerViewController. Below is code for sign in, but I have no idea how to tell which category the email belongs to. Thanks!
#IBAction func loginPressed(sender: AnyObject) {
if let email = emailField.text where email != "", let password = passwordField.text where password != "" {
FIRAuth.auth()?.signInWithEmail(email, password: password, completion: { (user, err) in
if err != nil {
print(err)
} else {
// Here I need to know whcih view Controller to Segue to:
self.performSegueWithIdentifier(identifier: String, sender: self)
}
}
Data Structure as below:
How about making your JSON like :-
yourApp:{
cooks:{
email1:true,
email3:true,
email4:true,
email7:true,
email8:true},
customers:{
email2:true,
email12:true,
email13:true,
email4:true,
email8:true},
users:{
uid1:{
email : blah#blah.com,
isCook: true
},
uid2:{
email : burp#blah.com,
isCook: false
}....
}
}
So you can either check in the cooks section or the customer section or the uid under users section itself and then relating to the isCook node, if he is ->Go to cookViewController, else go to customerViewController
Easiest way would be to check in the uid:-
FIRDatabase.database().reference().child("users/\(FIRAuth.auth()!.currentUser!.uid)/isCook").observeSingleEventOfType(.Value,withBlock:{(snap) in
if let isThisUserCook = snap.value as? Bool //or String{
if isThisUserCook == true{
//segue to cookVC
}else{
//segue to customerVC
}
}
})