"use of unresolved identifier 'myAlert & okAction' - swift

I keep receiving an error on 15th and 16th lines from the bottom. It tells me:
"use of unresolved identifier 'myAlert & okAction'"
If anyone can help, it would be much appreciated.
Code:
import UIKit
class RegisterPageViewController: UIViewController {
#IBOutlet weak var userNameTextField: UITextField!
#IBOutlet weak var userPhoneTextField: UITextField!;
#IBOutlet weak var userPasswordTextField: UITextField!;
#IBOutlet weak var userConfirmPasswordTextField: UITextField!;
#IBOutlet weak var userPlugTextField: UITextField!;
#IBAction func RegisterButtonTapped(_ sender: Any) {
let userName = userNameTextField.text;
let userPhone = userPhoneTextField.text;
let userPassword = userPasswordTextField.text;
let userConfirmPassword = userConfirmPasswordTextField.text;
let userPlug = userPlugTextField.text;
// Check for empty fields
if(userName!.isEmpty || userPhone!.isEmpty || userPassword!.isEmpty || userConfirmPassword!.isEmpty || userPlug!.isEmpty)
{
displayMyAlertMessage(userMessage: "All fields are required")
return;
}
// check if passwords match
if(userPassword != userConfirmPassword)
{
// Display an alert message
displayMyAlertMessage(userMessage: "Passwords do not match")
return;
}
// Store data
UserDefaults.standard.set(userName, forKey: "userName")
UserDefaults.standard.set(userName, forKey: "userPhone")
UserDefaults.standard.set(userName, forKey: "userPassword")
UserDefaults.standard.set(userName, forKey: "userPlug")
UserDefaults.standard.synchronize();
// Display alert message with confirmation
_ = UIAlertController(title:"Alert", message:"Registration is successful. Thank you!", preferredStyle: UIAlertControllerStyle.alert);
_ = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default){ action in
self.dismiss(animated: true, completion:nil)
}
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil)
}
func displayMyAlertMessage(userMessage:String)
{
let myAlert = UIAlertController(title:"Alert", message:userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default, handler:nil);
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}
}

Replace
_ = UIAlertController(title:"Alert", message:"Registration is successful. Thank you!", preferredStyle: UIAlertControllerStyle.alert);
_ = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default){ action in
self.dismiss(animated: true, completion:nil)
}
with
let myAlert = UIAlertController(title:"Alert", message:"Registration is successful. Thank you!", preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default){ action in
self.dismiss(animated: true, completion:nil)
}

You cannot 'see' those two objects because you are trying to reference them outside of their scope. Their scope is the function in which they are defined.
Not sure why you have those two lines at all, though, if you have
displayMyAlertMessage(userMessage:)

Related

How can I add alert button till my data count? How can I save my data choose from a action index?

I'm present a alert when I click the button. I choose from a list (if how much data is available.) How can I save my data choose from a list index?
You can see UI in here
My AccountServices
class AccountServices {
static let databaseReference = Database.database().reference(withPath: "Accounts").child((Auth.auth().currentUser?.uid)!)
static var account = Account()
static func saveChanges() {
databaseReference.setValue(try! FirebaseEncoder().encode(AccountServices.account))
}
static func getAccount() {
databaseReference.observeSingleEvent(of: .value, andPreviousSiblingKeyWith: { (snapshot, _) in
account = try! FirebaseDecoder().decode(Account.self, from: snapshot.value!)
})
}
}
Variable
var product: ProductViewModel?
addButton Tapped
#IBAction func addToCartButtonTapped(_ sender: UIButton) {
let alert = UIAlertController(title: "Bu ürünü hangi sepetinize eklemek istersiniz ?", message: "", preferredStyle: .actionSheet)
var indexer = 0
for cart in AccountServices.account.cart! {
if cart.product == nil{
AccountServices.account.cart![indexer].product = [Product]()
}
let action = UIAlertAction(title: cart.name , style: .default, handler: { (sender) in
if let index = alert.actions.firstIndex(where: { $0 === sender }) {
AccountServices.account.cart?[index].product?.append(self.product) `//Error: Cannot convert value of type 'ProductViewModel?' to expected argument type 'Product'`
AccountServices.saveChanges()//TODO...
}
let addAlert = UIAlertController(title: "Sepetinize Eklendi.", message: "Ürününüz sepetinize eklendi.", preferredStyle: .alert)
let okButton = UIAlertAction(title: "Tamam", style: .default, handler: nil)
addAlert.addAction(okButton)
self.present(addAlert, animated: true, completion: nil)
})
alert.addAction(action)
indexer += 1
}
let cancelaction = UIAlertAction(title: "Vazgeç", style: .cancel, handler: nil)
alert.addAction(cancelaction)
present(alert, animated: true, completion: nil)
}
}

objc[75927]: Class PFFile and objc[75927]: Class PFLogger is implemented in both One of the two will be used. Which one is undefined

No errors in my code, but the console is printing the title of this post. I am using parse as a server. I am using this exact same code in an example video that i learned from on Udemy. Also None of my buttons are working when they are connected properly.
import UIKit
import Parse
class ViewController: UIViewController {
var signUpMode = true
var activityIndicator = UIActivityIndicatorView()
#IBOutlet var emailTextField: UITextField!
#IBOutlet var passwordTextField: UITextField!
#IBOutlet var signUpOrLogin: UIButton!
#IBOutlet var changeSignUpMode: UIButton!
#IBOutlet var messageLabel: UILabel!
func createAlert(title:String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
//self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
#IBAction func signUpOrLogin(_ sender: Any) {
if emailTextField.text == "" || passwordTextField.text == "" {
createAlert(title: "Error due to form", message: "Please enter an Email and Password.")
} else {
activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.style = UIActivityIndicatorView.Style.gray
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.shared.beginIgnoringInteractionEvents()
if signUpMode{
let user = PFUser()
user.username = emailTextField.text
user.email = emailTextField.text
user.password = passwordTextField.text
user.signUpInBackground(block:{ (success, error) in
self.activityIndicator.stopAnimating()
UIApplication.shared.endIgnoringInteractionEvents()
if error != nil {
var displayErrorMessage = "Please try again later"
if let errorMessage = (error! as NSError).userInfo["error"] as? String {
displayErrorMessage = errorMessage
//This is the message that the console gives us
}
self.createAlert(title: "Signup Error", message: displayErrorMessage)
} else {
print("user signed up")
}
})
} else {
//login mode
PFUser.logInWithUsername(inBackground: emailTextField.text!, password: passwordTextField.text!) { (user, error) in
self.activityIndicator.stopAnimating()
UIApplication.shared.endIgnoringInteractionEvents()
if error != nil{
var displayErrorMessage = "Please try again later"
if let errorMessage = (error! as NSError).userInfo["error"] as? String {
displayErrorMessage = errorMessage
//This is the message that the console gives us
}
self.createAlert(title: "Login Error", message: displayErrorMessage)
} else {
print("logged in")
}
}
}
}
}
#IBAction func changeSignUpMode(_ sender: Any) {
if signUpMode{
//Change to Login Mode
signUpOrLogin.setTitle("Log In", for: [] ) //empty array is default state again....
changeSignUpMode.setTitle("Sign Up", for: [])
messageLabel.text = "Don't have an account?"
signUpMode = false
} else {
//Change to SignupMode
signUpOrLogin.setTitle("Sign Up", for: [])
changeSignUpMode.setTitle("Log In", for: [])
messageLabel.text = "Already have an account?"
signUpMode = true
}
}

Custom Auth using AWS Cognito, Swift

I am trying to use AWS Cognito for password less signin/signup using mobile number.
Signin/Signup steps:
User submits only mobile number
After receiving the passcode via sms, the user submits that to signin/signup.
To achieve the above, as there is no example code for mobile number only Signin, I am trying to amend the standard sign up (email, password) code shown in this aws sdk github example.
Can someone please advice what changes are to be made to achieve signin via mobile number only (no e-mail or username).
import Foundation
import AWSCognitoIdentityProvider
class SignUpViewController: UIViewController {
var pool: AWSCognitoIdentityUserPool?
var sentTo: String?
#IBOutlet weak var username: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var phone: UITextField!
#IBOutlet weak var email: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.pool = AWSCognitoIdentityUserPool.init(forKey: AWSCognitoUserPoolsSignInProviderKey)
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: false)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let signUpConfirmationViewController = segue.destination as? ConfirmSignUpViewController {
signUpConfirmationViewController.sentTo = self.sentTo
signUpConfirmationViewController.user = self.pool?.getUser(self.username.text!)
}
}
#IBAction func signUp(_ sender: AnyObject) {
guard let userNameValue = self.username.text, !userNameValue.isEmpty,
let passwordValue = self.password.text, !passwordValue.isEmpty else {
let alertController = UIAlertController(title: "Missing Required Fields",
message: "Username / Password are required for registration.",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
return
}
var attributes = [AWSCognitoIdentityUserAttributeType]()
if let phoneValue = self.phone.text, !phoneValue.isEmpty {
let phone = AWSCognitoIdentityUserAttributeType()
phone?.name = "phone_number"
phone?.value = phoneValue
attributes.append(phone!)
}
if let emailValue = self.email.text, !emailValue.isEmpty {
let email = AWSCognitoIdentityUserAttributeType()
email?.name = "email"
email?.value = emailValue
attributes.append(email!)
}
//sign up the user
self.pool?.signUp(userNameValue, password: passwordValue, userAttributes: attributes, validationData: nil).continueWith {[weak self] (task) -> Any? in
guard let strongSelf = self else { return nil }
DispatchQueue.main.async(execute: {
if let error = task.error as? NSError {
let alertController = UIAlertController(title: error.userInfo["__type"] as? String,
message: error.userInfo["message"] as? String,
preferredStyle: .alert)
let retryAction = UIAlertAction(title: "Retry", style: .default, handler: nil)
alertController.addAction(retryAction)
self?.present(alertController, animated: true, completion: nil)
} else if let result = task.result {
// handle the case where user has to confirm his identity via email / SMS
if (result.user.confirmedStatus != AWSCognitoIdentityUserStatus.confirmed) {
strongSelf.sentTo = result.codeDeliveryDetails?.destination
strongSelf.performSegue(withIdentifier: "confirmSignUpSegue", sender:sender)
} else {
let _ = strongSelf.navigationController?.popToRootViewController(animated: true)
}
}
})
return nil
}
}
}

User Login & Register Problems

Trying to set up Login and Register Controllers but I keep getting the same errors and all the solutions online have been no help. The Errors appear on lines: "displayMyAlertMessage" and UserDefaults.
#IBAction func signUpButton(_ sender: Any) {
let userName = userFirstName.text;
let userLast = userLastName.text;
if(userName!.isEmpty || userLast!.isEmpty)
{
displayMYAlertMessage("All Fields are RequireD");
return;
}
// Store data
UserDefaults.standardUserDefaults().setObject("userName", forKey: "userName")
UserDefaults.standardUserDefaults().setObject("userLast", forKey: "userLast")
let userName = UserDefaults.standardUserDefaults().stringForKey("userName")
let userLast = UserDefaults.standardUserDefaults().stringForKey("userLast")
// Display alert message with confirmation.
var myAlert = UIAlertController(title:"Alert", message:"Registration is successful. Thank you!", preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default){ action in
self.dismiss(animated: true, completion:nil);
}
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}
}

use of unresolved identifier 'result' swift 3

I'm writing a login page for my app and i'm getting this error
social media app , xcode 8.3.2 , swift 3
i've tried target membership in file inspector and nothing changed
also I removed test units (UITest and Test) and renew them , it didn't worked either.
at the line 41 I'm getting this error "use of unresolved identifier 'result'"
the picture below explains the code
Picture
import UIKit
class LoginViewController : UIViewController
{
#IBOutlet weak var txt_username: UITextField!
#IBOutlet weak var txt_password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func btn_log_in_click(_ sender: Any){
let server=MultipartUtility (Url:"http://x.x.x.x/appname-api/user/login/")
//I.m hiding the real ip and details for posting this
server.AddFormField("username", value: txt_username.text)
server.AddFormField("password", value: txt_password.text)
let task = URLSession.shared.dataTask(with: server.execute())
{Data,URLResponse,error in
if error != nil{
print(error as Any)
return
}
do{
let json = try JSONSerialization.jsonObject(with: Data!, options: .allowFragments)
if let json_result = json as? [String: Any]{
let result = json_result ["result"] as? String
if result == "0"
{
DispatchQueue.main.async {
let alert = UIAlertController(title:"Incorrect Username",message : "The username you entered doesn't appear to belong to an account. Please check your username and try again", preferredStyle : .alert)
let alert_action = UIAlertAction(title: "Try Again", style: .default, handler: nil)
alert.addAction(alert_action)
self.present(alert, animated: true, completion: nil)
}
}
}
else{
DispatchQueue.main.async {
UserDefaults.standard.set(result!, forKey: "user_id")
//" use of unresolved identifier 'result' "
let current_view=UIApplication.shared.windows[0] as UIWindow
let new_view=(self.storyboard? .instantiateViewController(withIdentifier: "tab_bar"))! as UIViewController
UIView.transition(from: (current_view.rootViewController? .view)!, to:new_view.view , duration: 0.65, options: .transitionFlipFromRight, completion: {(action) in current_view.rootViewController=new_view
})
}
}
}
catch{
}
}
task.resume()
}
}
if let json_result = json as? [String: Any]
{
let result = json_result ["result"] as? String
if result == "0"
{
DispatchQueue.main.async {
let alert = UIAlertController(title:"Incorrect Username",message : "The username you entered doesn't appear to belong to an account. Please check your username and try again", preferredStyle : .alert)
let alert_action = UIAlertAction(title: "Try Again", style: .default, handler: nil)
alert.addAction(alert_action)
self.present(alert, animated: true, completion: nil)
}
}
else
{
DispatchQueue.main.async {
UserDefaults.standard.set(result!, forKey: "user_id")
//" use of unresolved identifier 'result' "
let current_view=UIApplication.shared.windows[0] as UIWindow
let new_view=(self.storyboard? .instantiateViewController(withIdentifier: "tab_bar"))! as UIViewController
UIView.transition(from: (current_view.rootViewController? .view)!, to:new_view.view , duration: 0.65, options: .transitionFlipFromRight, completion: {(action) in current_view.rootViewController=new_view
})
}
}
}
else{
// Error in jsonSerialization
}