Getting data from Parse as “Optional(test)” and want to do something with that “test” part - swift

I am new to Parse and I am trying to retrieve my first password (my password is: test). But I can only receive it as “Optional(test)”. The “test” there is actually the password that I want to receive but I can’t get it out of the paranthesis. My code is as follows;
import UIKit
import Parse
import Bolts
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var userNameTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var credentialsLabel: UILabel!
#IBAction func checkCredentialsButton(sender: AnyObject) {
var query = PFQuery(className:"userName")
query.getObjectInBackgroundWithId("the id of my object") {
(userNameRetrieved: PFObject?, error: NSError?) -> Void in
if error == nil && userNameRetrieved != nil {
println(userNameRetrieved)
println("Username has been retrieved succesfully")
println(userNameRetrieved?.objectForKey("username"))
} else {
println(error)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.userNameTextField.delegate = self
self.passwordTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(userText: UITextField) -> Bool {
userNameTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
return true
}
}
And my logs are as follows;
Optional(<userName: "my username", objectId: “the id that i am using", localId: (null)> {
ACL = "<PFACL: “my acl">";
username = test;
})
Username has been retrieved succesfully
Optional(test)
Is there a way for me to use that password to log my user in?
Also, is there a way for me to retrieve an array of passwords that are registered to check if the password is true or not?

use if let to unwrap the optional
#IBAction func checkCredentialsButton(sender: AnyObject) {
var query = PFQuery(className:"userName")
query.getObjectInBackgroundWithId("the id of my object") {
(userNameRetrieved: PFObject?, error: NSError?) -> Void in
if error == nil && userNameRetrieved != nil {
if error == nil && userNameRetrieved != nil {
if let userArray = userNameRetrieved {
print(userArray)
if let username = userNameRetrieved?.objectForKey("username") {
print(username)
}
}
} else {
println(error)
}
}
}

Related

How to retrieve and show user data from Firebase with swift?

I followed a tutorial to create a register and login screen with firebase and is already working, but now I want to create the screen "My account" with text fields where show the name, mail, etc.. of the user, so my question and I need help is how to get the data from firebase and show that information on that screen, how can I do it please?
I already read the firebase documentation https://firebase.google.com/docs/auth/ios/manage-users but I don't know how to proceed because Im learning programming/swift and I have to still improving my level
I attach the code of the sign up view
import UIKit
import FirebaseAuth
import FirebaseFirestore
import Firebase
class SignUpViewController: UIViewController {
#IBOutlet weak var nameField: UITextField!
#IBOutlet weak var lastNameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var signUpButton: UIButton!
#IBOutlet weak var errorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setUpElements()
}
func setUpElements(){
//Hide the error label
errorLabel.alpha = 0
//Style the elements
Utilities.styleTextField(nameField)
Utilities.styleTextField(lastNameField)
Utilities.styleTextField(emailField)
Utilities.styleTextField(passwordField)
Utilities.styleFilledButton(signUpButton)
}
// Check the fields and validate that the data is correct. If everything is correct, this method returns nil. Otherwise, it returns the error message
func validateFields() -> String? {
// Check that all fields are filled in
if nameField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
lastNameField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
emailField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
passwordField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
return "Please fill in all fields."
}
// Check if the password is secure
let cleanedPassword = passwordField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
if Utilities.isPasswordValid(cleanedPassword) == false {
// Password isn't secure enough
return "Please make sure your password is at least 8 characters, contains a special character and a number."
}
return nil
}
#IBAction func signUpTapped(_ sender: Any) {
// Validate the fields
let error = validateFields()
if error != nil {
// There's something wrong with the fields, show error message
showError(error!)
}
else {
// Create cleaned versions of the data
let firstName = nameField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let lastName = lastNameField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let email = emailField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let password = passwordField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
// Create the user
Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
// Check for errors
if err != nil {
// There was an error creating the user
self.showError("Error creating user")
}
else {
// User was created successfully, now store the first name and last name
let db = Firestore.firestore()
db.collection("users").addDocument(data: ["firstname":firstName, "lastname":lastName, "uid": result!.user.uid ]) { (error) in
if error != nil {
// Show error message
self.showError("Error saving user data")
}
}
// Transition to the home screen
self.transitionToHome()
}
}
}
}
func showError(_ message:String) {
errorLabel.text = message
errorLabel.alpha = 1
}
func transitionToHome() {
let homeViewController = storyboard?.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as? HomeViewController
view.window?.rootViewController = homeViewController
view.window?.makeKeyAndVisible()
}
}
And the actual code of my account view controller, just I add it the text fields, I don't know how to proceed
import UIKit
class MyAccountViewController: UIViewController {
#IBOutlet weak var nameField: UITextField!
#IBOutlet weak var lastnameField: UITextField!
#IBOutlet weak var emailField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
I think that I provided all the info necessary, thank you

How to make a correct authorization

i am making an app Redmine, i have a website with a user with pass and there are issues. But i can't understand what i should do to make authorization.
Here I have Router, Request, AuthViewController. I also wanted to ask how i have to make AuthRequest? What has to be there?
AuthViewController
import UIKit
class AuthViewController: UIViewController {
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var signInBotton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func signInDidTap(_ sender: Any) {
login()
}
fileprivate func login(){
AuthRequest.login(email: emailField.text!, password: passwordField.text!){(user, error) in DispatchQueue.main.async {
[unowned self] in self.openIssues()
}
}
}
}
//extension AuthViewController: Router{
// func prepare() {
// Here error with 'seque' if(seque.identifier = Seque.issues.rawValue){
// print("It's OK")
// guard let controller = seque.destination as? IssuesViewController else { print("Wrong destination"); return}
// //controller.presenter = IssuesPresenter();
// }
// }
//
// func openIssues() {
// print("kek")
// }
//
//
// enum Seque: String {
// case issues = "IssuesSeque"
// }
//
//}
There is also an error in if-block in extension.

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.

Why won't swift recalculate the 'if' statement?

I'm trying to create a very simple 'guessing game' where the user has to guess how many fingers the computer has up (maximum 5 fingers).
Here's the thing. When the code executes and I press submit, even when the print logs registers a correct number, the app still prints the if statement for incorrect. Where am I going wrong?
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var fingerInput: UITextField!
#IBOutlet weak var fingerResult: UILabel!
#IBAction func fingerSubmit(sender: AnyObject) {
let realNumberofFingers = Int(arc4random_uniform(6))
print(realNumberofFingers)
if fingerInput != realNumberofFingers {
fingerResult.text = "Gosh darn, that's wrong!"
} else if fingerInput == realNumberofFingers {
fingerResult.text = "Thats right!"
}
}
}
You are comparing the actual UITextField fingerInput with the realNumberofFingers. That is wrong and will always yield false. What you should do instead is parse the string from the fingerInput and check if the integer contained in that string is equal to realNumberofFingers:
#IBAction func fingerSubmit(sender: AnyObject) {
let input = Int(fingerInput.text!)
if let enteredFingers = input {
let realNumberofFingers = Int(arc4random_uniform(6))
print(realNumberofFingers)
if enteredFingers == realNumberofFingers {
fingerResult.text = "Thats right!"
} else {
fingerResult.text = "Gosh darn, that's wrong!"
}
} else {
fingerResult.text = "Please enter a correct guess - an integer!"
}
}

FBLoginManager undeclared type

I installed FacebookSDK using Cocoapods, according to Terminal, I have installed FacebookSDK 4.8.0 (CoreKit, ShareKit and LoginKit), I imported the .h files in my BH-File.h, and already initialized everything in my AppDelegate.
For some reason, when trying to log in using a custom button, when I initialize FBLoginManager, I get an error Use of undeclared type "FBLoginManager".
this is my code
if (FBSDKAccessToken.currentAccessToken() == nil)
{
let fbLoginManager : FBSDKLoginManager =
fbLoginManager.logInWithReadPermissions(["public_profile", "email"], fromViewController: self, handler: { (loginResult, error) -> Void in
if error == nil {
print (FBSDKAccessToken.currentAccessToken().tokenString)
}
else {
print ("ERROR*****: \(error)")
}
})
}
What fixed to me was adding import FBSDKCoreKit and FBSDKLoginKit to my class, for some reason is not enough adding it in the BH-file.h
Try something like this, I just checked the code and it works (it's not exactly what you're looking for but I'm sure you can modify it as needed)
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class ProfileViewController: UIViewController,FBSDKLoginButtonDelegate {
// #IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var nextButton: UIButton!
#IBOutlet weak var fbLoginButton: FBSDKLoginButton!
override func viewDidLoad() {
super.viewDidLoad()
self.fbLoginButton.delegate = self
self.fbLoginButton.readPermissions = ["public_profile"]
self.fbLoginButton.publishPermissions = ["publish_actions"]
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "fbProfileChanged:",
name: FBSDKProfileDidChangeNotification,
object: nil)
FBSDKProfile.enableUpdatesOnAccessTokenChange(true)
// If we have a current Facebook access token, force the profile change handler
if ((FBSDKAccessToken.currentAccessToken()) != nil)
{
self.fbProfileChanged(self)
} }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
//facebooks functions
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
if (error != nil)
{
print( "\(error.localizedDescription)" )
}
else if (result.isCancelled)
{
// Logged out?
print( "Login Cancelled")
}
else
{
// Logged in?
print( "Logged in, segue now")
self.performSegueWithIdentifier("showHome", sender: self)
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
}
//see bitfountain
func fbProfileChanged(sender: AnyObject!) {
let fbProfile = FBSDKProfile.currentProfile()
if (fbProfile != nil)
{
// Fetch & format the profile picture
let strProfilePicURL = fbProfile.imagePathForPictureMode(FBSDKProfilePictureMode.Square, size: imageView.frame.size)
let url = NSURL(string: strProfilePicURL, relativeToURL: NSURL(string: "http://graph.facebook.com/"))
let imageData = NSData(contentsOfURL: url!)
let image = UIImage(data: imageData!)
self.nameLabel.text = fbProfile.name
self.imageView.image = image
self.nameLabel.hidden = false
self.imageView.hidden = false
self.nextButton.hidden = false
}
else
{
self.nameLabel.text = ""
self.imageView.image = UIImage(named: "")
self.nameLabel.hidden = true
self.imageView.hidden = true
}
}
#IBAction func nextButtonPressed(sender: UIButton) {
self.performSegueWithIdentifier("showHome", sender: self)
}
}