How to make a correct authorization - swift

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.

Related

displaying user email on viewcontroller gives optional"email adress" [duplicate]

This question already has answers here:
How to remove optional text from json Result In swift
(3 answers)
Optional Text in Alert in ResetPassword - iOS Project using Swift
(2 answers)
Closed 1 year ago.
So I'm using firebase Authentication in my ios app, and I want to display the email address, and Username in UIlabels on a viewcontroller. But when i display the value of Auth.auth().email on a UIlabel, the Label would show Optional"email adress".How do i get rid of the Optional and also how to allow the user to have a display name in firebase Authentication?
import Firebase
import FirebaseAuth
class ProfileViewController: UIViewController {
#IBOutlet weak var profiepic: UIImageView!
#IBOutlet weak var UsernameLabel: UILabel!
#IBOutlet weak var EmailLabel: UILabel!
#IBOutlet weak var league: UILabel!
#IBOutlet weak var Achievements: UIButton!
#IBOutlet weak var resetpasswd: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
UsernameLabel.layer.borderColor = UIColor.black.cgColor
EmailLabel.layer.borderColor = UIColor.black.cgColor
league.layer.borderColor = UIColor.black.cgColor
Achievements.layer.cornerRadius = 55/2
resetpasswd.layer.cornerRadius = 55/2
resetpasswd.layer.borderColor = UIColor.black.cgColor
displayinfo()
}
func displayinfo() {
let user = Auth.auth().currentUser
if let user = user {
// The user's ID, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server,
// if you have one. Use getTokenWithCompletion:completion: instead.
let email = user.email
let photoURL = user.photoURL
EmailLabel.text = "Email: \(email)"
// ...
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
You need to use if or guard to display string info properly.
Using if:
func displayinfo() {
let user = Auth.auth().currentUser
if let user = user {
if let email = user.email {
EmailLabel.text = "Email: \(email)"
}
if let photoURL = user.photoURL {
...
}
// ...
}
}
Using guard:
func displayinfo() {
guard let user = Auth.auth().currentUser else {
print("No user info found")
return
}
if let email = user.email {
EmailLabel.text = "Email: \(email)"
//EmailLabel.text = "Email: " + email
}
if let photoURL = user.photoURL {
...
}
// ...
}
Let me know if you have any issue in these solutions.
Apart from this, I would rather write UIViewController in this manner which seems to be a more clearer approach.
class ProfileViewController: UIViewController {
#IBOutlet weak var profiepic: UIImageView!
#IBOutlet weak var lblUsername: UILabel! {
didSet {
lblUsername.layer.borderColor = UIColor.black.cgColor
}
}
#IBOutlet weak var lblEmail: UILabel! {
didSet {
lblEmail.layer.borderColor = UIColor.black.cgColor
}
}
#IBOutlet weak var lblLeague: UILabel! {
didSet {
lblLeague.layer.borderColor = UIColor.black.cgColor
}
}
#IBOutlet weak var btnAchievements: UIButton! {
didSet {
btnAchievements.layer.cornerRadius = 55/2
// For button height, instead of 55 here you can use, btnAchievements.bounds.height / 2 or use constrain also to change button height when bound changes
}
}
#IBOutlet weak var btnReset: UIButton! {
didSet {
btnReset.layer.cornerRadius = 55/2
btnReset.layer.borderColor = UIColor.black.cgColor
}
}
private var currentUser: AuthUser? {// Type of Auth.auth().currentUser
didSet {
// Use above code for displayInfo or simply call displayInfo from here
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.currentUser = Auth.auth().currentUser
}
...
}
I hope this would help you designing other UIViewControllers as well.

Is there a way to throw errors from firebase login to error handling?

I have one class that i call RealTimeAPI and then the actual LoginViewController class and what i want to do is i want to add my register method in my RealtimeApi class and call register in my LoginView. But then i need to errorhandle in my LoginView so i need to throw the error from the completionhandler in the registerfunction RealtimeAPIs Createuser. is this possible or no? this is my code so far.
RealtimeAPIClass
import Foundation
import Firebase
enum RegisterError: Error
{
case IncompleteForm
case NonMatchingForm
case FirebaseError
}
class RealTimeApi
{
private let Reference: DatabaseReference! = Database.database().reference()
private var nilOrNot = [Bool]()
public var errorDescription: String?
func Register(FullName: String?, Username: String?, Email: String?, EmailVerification: String?, Password: String?, PasswordVerification: String? )
{
Auth.auth().createUser(withEmail: Email!, password: Password, completion: er, Error){
}
}
func Login(Username:String, Password: String)
{
}
func CheckLoggedinUser() -> Bool
{
let currentuser = Auth.auth().currentUser
if(currentuser == nil)
{
return false
}else{
return true
}
}
}
Loginview
import UIKit
import Firebase
class LogInV: UIViewController {
#IBOutlet weak var UsernameTxt: UITextField!
#IBOutlet weak var PasswordTxt: UITextField!
#IBOutlet var TextfieldRegistrationCollection: [UITextField]!
#IBOutlet weak var ImageView: UIView!
#IBOutlet weak var RegisterView: UIView!
#IBOutlet weak var RV_VerticalAlignmentConstraint: NSLayoutConstraint!
#IBOutlet weak var RegisterBtnO: UIButton!
var Data = RealTimeApi()
var TextFieldStyle = TextfieldStyling()
override func viewDidLoad() {
super.viewDidLoad()
TextFieldStyle.StylizeTextField(StylizedTextField: UsernameTxt)
TextFieldStyle.StylizeTextField(StylizedTextField: PasswordTxt)
for i in 0...TextfieldRegistrationCollection.count - 1 {
TextFieldStyle.StylizeTextField(StylizedTextField: TextfieldRegistrationCollection[i])
}
TextfieldValidation()
RV_VerticalAlignmentConstraint.constant += view.bounds.height
}
override func viewDidAppear(_ animated: Bool) {
RegisterBtnO.isEnabled = false
}
#IBAction func LoginButtons(_ sender: UIButton) {
switch sender.tag{
case 0:
break
case 1:
Slide()
break
default:
print("button not pressed")
break
}
}
func Slide()
{
UIView.animate(withDuration: 1, delay: 0, options: .curveEaseIn, animations: {
self.RV_VerticalAlignmentConstraint.constant -= self.view.bounds.height
self.view.layoutIfNeeded()
}, completion: nil)
}
#IBAction func RegisterBtn(_ sender: UIButton) {
}
//Validate textfields so that user register does not work for empty input
func TextfieldValidation()
{
for i in 0...TextfieldRegistrationCollection.count - 1
{
TextfieldRegistrationCollection[i].addTarget(self, action: #selector(LogInV.textFieldDidChange), for: UIControlEvents.editingChanged)
}
}
//selector function for controlling empty textfield
#objc func textFieldDidChange(){
var NoneIsEmpty = Int()
for i in 0...TextfieldRegistrationCollection.count - 1{
if let text = TextfieldRegistrationCollection[i].text, text.isEmpty == false {
NoneIsEmpty += 1
}
}
if(NoneIsEmpty == TextfieldRegistrationCollection.count)
{
RegisterBtnO.isEnabled = true
}else{
RegisterBtnO.isEnabled = false
}
NoneIsEmpty = 0
}
func showAlert(error: String)
{
let Erroralert = UIAlertController(title: "Error", message: error, preferredStyle: .alert)
Erroralert.addAction(UIAlertAction(title: "Dissmiss",style: .cancel ,handler: {action in
print("tapped actionbutton")
}))
present(Erroralert, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
}
}
func UploadCustomerList(customer: Customer)
{
}
}
So basically i want to do something like this
Auth.auth().createUser(withEmail: Email!, password: Password, completion: User, Error){
throw Error
}
I have created a helper class with the following method:
func setupAlert(with title: String, with message: String?, viewController: UIViewController) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancel = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(cancel)
viewController.present(alert, animated: true, completion: nil)
}
you must pass the viewcontroller in the parameter where you want to display the alert. Then you can also pass the error, which can be found in Auth.auth()

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)
}
}

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

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)
}
}
}

Changing the view color when comparing values

I created a view to use as background and I would like to change its color when label text is greater or less than variable number. The script is okay but the color is not changing.
Thanks in advance.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var localName: UITextField!
#IBOutlet weak var localNameLabel: UILabel!
#IBOutlet weak var localTemp: UILabel!
#IBAction func getData(sender: AnyObject) {
getWeatherData("http://api.openweathermap.org/data/2.5/weather?q=" + localName.text! + "")
}
#IBOutlet weak var fundo: UIView!
override func viewDidLoad() {
super.viewDidLoad()
getWeatherData("http://api.openweathermap.org/data/2.5/weather?q=London")
// 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.
}
func getWeatherData(urlString: String){
let url = NSURL (string: urlString)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
dispatch_async(dispatch_get_main_queue(), {
self.setLabels(data!)
})
}
task.resume()
}
func setLabels(weatherData: NSData) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(weatherData, options:NSJSONReadingOptions.MutableContainers) as! NSDictionary
print(json)
//localNameLabel.text = json[("name")] as? String
if let name = json[("name")] as? String {
localNameLabel.text = name
}
if let main = json[("main")] as? NSDictionary {
if let temp = main[("temp")] as? Double {
//convert kelvin to celsius
let ft = (temp - 273.15)
let myString = ft.description
localTemp.text = myString
self.changeColor()
}
}
} catch let error as NSError {
print(error)
}
var number : Float
func changeColor(){
number = 19.0
if(Float(localTemp.text!) < number){
fundo.backgroundColor = .blueColor()
}else{
fundo.backgroundColor = .orangeColor()
}
}
}
}
Edited to post the entire script
In your view controller you need to add UITextFieldDelegate which will allow you to access methods related to your text field. The top of your view controller should look like this:
class ViewController: UIViewController,UITextFieldDelegate //set delegate to class
You then need to set the delegate of your text field to self in viewDidLoad and add a target for when the text field changes:
override func viewDidLoad() {
super.viewDidLoad()
localTemp.delegate = self //set delegate to this vc
localTemp.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
}
You can then implement this method which will run on every key press and you need to call your changeColor() method as above:
func textFieldDidChange(textField: UITextField) {
self.changeColor()
}