Displaying an alert in Swift - swift

I'm learning swift and I'm building a UI for an app, I wanted to know what was wrong with my code because it keeps saying I have errors.
let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;
let userRepeatPassword = repeatPasswordTextField.text;
// check for empty fields
if((userEmail.isEmpty || userPassword.isEmpty || userRepeatPassword.isEmpty)
{
//Display alert message
displayMyAlertMessage("Alert fields are required");
return;
}
//check if passwords match
if(userPassword != userRepeatPassword)
// error expected expression in list of expression
{
//Display alert message
displayMyAlertMessage("Alert fields are required");
return;
}
expected '(" after if condition
func displayMyAlertMessage(userMessage: String)
{
var myAlert = UIAlertController(
title: "Alert",
message: userMessage,
PrefferedStyle:UIAlertController.Alert);
}
error Type"UIAlertController'has no member 'Alert'
Just need help figuring out the errors for the code

This code line of yours:
var myAlert = UIAlertController(title:"Alert", message:
userMessage, PrefferedStyle:UIAlertController.Alert);
should be:
var myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: .Alert);
Alert is a case of the enum UIAlertControllerStyle, so it should be UIAlertControllerStyle.Alert instead of UIAlertController.Alert. Additionally, because the compiler know what type of enum the parameter "preferredStyle" expect, so you can use .Alert instead.
There are more '(' than ')' in your first if condition:
if((userEmail.isEmpty || userPassword.isEmpty ||
userRepeatPassword.isEmpty) {
thus causing the first error. You should change it to:
if(userEmail.isEmpty || userPassword.isEmpty ||
userRepeatPassword.isEmpty) {
And to follow Swift coding convention, you should finally change it to:
if userEmail.isEmpty || userPassword.isEmpty ||
userRepeatPassword.isEmpty {

let userEmail = userEmailTextField.text
let userPassword = userPasswordTextField.text
let userRepeatPassword = repeatPasswordTextField.text
// check for empty fields
if userEmail.isEmpty || userPassword.isEmpty ||
userRepeatPassword.isEmpty {
//Display alert message
displayMyAlertMessage("Alert fields are required")
return;
}
//check if passwords match
if userPassword != userRepeatPassword
//error expected expression in list of expression
{
//Display alert message
displayMyAlertMessage("Alert fields are required")
return
}
You do not need () after if statements in swift. Swift might consider them as tuples. You can just do
if condition {
}
Also you do not need semicolon after each statement in swift. You can remove ;

#Dat Hoang answer is correct but your alert actually won't show up until you present it. Add this line towards the end of your displayMyAlertMessage method
present(self, animated: true, completion: nil)
I'd recommend you check out this Swift Coding Styling Guide as well

Related

Document ID retrieval

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

linking of If Else Statements with picker

Beginner coder here. I have a question with Xcode. I am developing a horoscope app and have a question on linking my If Else Statements with picker input values.
The logic in the app currently is, User selects date listed, hits button, and an alert message pops up containing specific copy related to their input. How would I get my if else statements to print in the alert message?
TLDR; Need help with linking function print value with alert window message
Here is a sample of how it currently looks, I am also getting an error of [Cannot convert value of type '()' to expected argument type 'String?'] in line 3 here. Thank you in advance!
let message = signselection()
let alert = UIAlertController (title: "Your Astrological Sign is...", message:message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) {(action) -> Void in}
func signselection () {
if (curMonth == 0) {
if(curDay! < 20) {
print("Capricorn Message")
} else {
print("Aquarius Message")
}
}
if (curMonth == 1){
if(curDay! < 19) {
print ("Aquarius Message")
} else {
print ("Pisces Message")
} }
if (curMonth == 2){
if(curDay! < 20) {
print ("Pisces Message")
} else {
print ("Aries Message")
} }
The signselection() method only prints the message, but it should return a string. That's why you're getting the error saying that it can't cast void, "()", to String. The function declaration should be:
func signSelection() -> String
and in stead of print("Message") you should
return "Message" //where "Message" is each message you're currently printing
You should also add the okAction to there alert with:
alert.addAction(okAction)

How to specify the type of text in UITextField

I'm trying to determine whether or not a user is entering a proper email address into a UITextField . I'm using this code but am getting the following error message.
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch) // I'm getting the error message here.
let result = range != nil ? true : false
return result
}
#IBAction func logIn(sender: AnyObject) {
let validLogin = isValidEmail(testStr: field.text!)
if validLogin {
print("User entered valid input")
} else {
print("Invalid email address")
}
}
This is the error message I'm getting: "Value of type 'String' has no member 'rangeOfString'"
I think this is because I don't have RegExKitLite installed but I'm not 100% sure. Even so, I tried installing the kit but I couldn't figure out how. I downloaded the file but I can't figure out how to add it in Xcode.
If you are using Swift 3 or later, the lines:
let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
let result = range != nil ? true : false
return result
needs to be:
let range = testStr.range(of: emailRegEx, options: [ .regularExpression ])
return range != nil
None of this needs a third party library.
You probably also want to make sure the whole string matches so you should add ^ to the start of the regular expression and add $ to the end.

Deleting PFUser objects from database in swift

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.

optional type 'Bool' cannot be used as a boolean; Test for '!=nil' instead

optional type 'Bool' cannot be used as a boolean; Test for '!=nil' instead
I got an error at first if, by replacing the if condition (after), the second if condition did never run. Any idea?
Before:
if(userEmail?.isEmpty || userPassword?.isEmpty || userRepeatPassword?.isEmpty){
displayMyAlertMessage("All fields are required")
return
}
if(userPassword != userRepeatPassword){
displayMyAlertMessage("Passwords do not match.")
}
After:
if(userEmail != nil || userPassword != nil || userRepeatPassword != nil){
displayMyAlertMessage("All fields are required")
return
}
if(userPassword != userRepeatPassword){
displayMyAlertMessage("Passwords do not match.")
}
you need to wrapped it with ! instead of ?.
That will solved the error message:
if (username!.isEmpty) .....
if(userEmail!.isEmpty || userPassword!.isEmpty || userRepeatPassword!.isEmpty)
You can't check the value of an optional since , you probably already know, being an optional implies it can or cannot be there. One solution is called force unwrapping and it is being done by using an "!" ( exclamation mark ). "?" ( question mark ) just lets the compiler know there may be or may not be a value so using the "!" we tell the compiler we know it may or it may not be a value inside that variable BUT we know there will be one, even if it's an EMPTY STRING, unlike other programming languages that consider empty strings, or empty arrays like "false". That's not the case in swift.
Your expression inside a conditional statement MUST be a valid boolean result.
You are checking if the value is different of nil and returning if it is, based un your comments and your second if you probably want to check if it is nil.
println("Checking login details")
if(userEmail.isEmpty || userPassword.isEmpty || userRepeatPassword.isEmpty){
displayMyAlertMessage("All fields are required")
println("Fail to login not all fields where fill")
return
} else if(userPassword != userRepeatPassword){
displayMyAlertMessage("Passwords do not match.")
println("Fail to login password does not match")
} else {
var uiAlert = UIAlertController(title: "Alert", message: "Registration was successful", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(uiAlert, animated: true, completion: nil)
uiAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
dismissViewControllerAnimated(true, completion:nil)
}))
}
With optional booleans, it works a little differently, you need to check explicitly if the value is nil. So that is exactly why your After: works and not your Before:
//now this is checking if your values are nil (empty) rather than not nil
//before if a user had valid fields, it would say that "All fields are required"
//now, this will work
if(userEmail == nil || userPassword == nil || userRepeatPassword == nil){
displayMyAlertMessage("All fields are required")
} else if(userPassword != userRepeatPassword){
displayMyAlertMessage("Passwords do not match.")
} else {
//success
//perform segue here to correct screen
}
There are a couple of options of how you can perform a segue, I will choose to use the presentViewController method, see below on how to integrate that.
...
else {
//success
//perform segue here to correct screen
presentViewController(yourMainScreenViewController, animated: true, completion: nil)
}
You could also use the
performSegueWithIdentifier("yourMainScreenIdentifier", sender: nil) if you don't use the presentViewController method, like:
else {
//success
//perform segue here to correct screen
performSegueWithIdentifier("yourMainScreenIdentifier", sender: nil)
}
I will add in what I assume your displayMyAlertMessage is:
func displayMyAlertMessage(alert: String) {
println(alert)
}