SHARE
TWEET

Untitled

a guest Jun 5th, 2017 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  LoginView.swift
  3. //  UserRegistrationExample
  4. //
  5. //  Created by Simo Korpikoski on 04/04/17.
  6. //  Copyright © 2017 Simo Korpikoski. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10. import UIKit
  11. import FBSDKLoginKit
  12. import Firebase
  13. import FirebaseAuth
  14.  
  15. let defaults = UserDefaults.standard
  16.  
  17. var facebookdata : [String : AnyObject]!
  18. var firstname = String()
  19. var lastname = String()
  20. var fbid = String()
  21. var currentId = String()
  22.  
  23. class LoginViewController: UIViewController, UITextFieldDelegate {
  24.    
  25.     var dict : [String : AnyObject]!
  26.     var tableData: NSArray = NSArray()
  27.     var userEmailInput = String()
  28.    
  29.     @IBOutlet weak var usernameTextField: UITextField!
  30.     @IBOutlet weak var userpasswordTextField: UITextField!
  31.     @IBOutlet weak var loginButton: UIButton!
  32.    
  33.     override func viewDidLoad() {
  34.         super.viewDidLoad()
  35.        
  36.         //initialize textfields for customization
  37.         self.usernameTextField.delegate = self
  38.         self.userpasswordTextField.delegate = self
  39.        
  40.         //initialize login button as unabled and check for changes in text fields
  41.         loginButton.isEnabled = false
  42.         usernameTextField.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
  43.         userpasswordTextField.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
  44.        
  45.        
  46.     }
  47.    
  48.     //Login Button functions
  49.     @IBAction func loginButtonTapped(_ sender: AnyObject) {
  50.        
  51.         if self.usernameTextField.text == "" || self.userpasswordTextField.text == "" {
  52.            
  53.             //Alert to tell the user that there was an error because they didn't fill anything in the textfields because they didn't fill anything in
  54.            
  55.             let alertController = UIAlertController(title: "Error", message: "Lisää sähköposti ja salasana.", preferredStyle: .alert)
  56.            
  57.             let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
  58.             alertController.addAction(defaultAction)
  59.            
  60.             self.present(alertController, animated: true, completion: nil)
  61.            
  62.         } else {
  63.            
  64.             FIRAuth.auth()?.signIn(withEmail: self.usernameTextField.text!, password: self.userpasswordTextField.text!) { (user, error) in
  65.                
  66.                 if error == nil {
  67.                    
  68.                     //Print into the console if successfully logged in
  69.                     print("You have successfully logged in")
  70.                    
  71.                     //Go to the HomeViewController if the login is sucessful
  72.                     let vc = self.storyboard?.instantiateViewController(withIdentifier: "profile")
  73.                     self.present(vc!, animated: true, completion: nil)
  74.                    
  75.                 } else {
  76.                    
  77.                     //Tells the user that there is an error and then gets firebase to tell them the error
  78.                     let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
  79.                    
  80.                     let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
  81.                     alertController.addAction(defaultAction)
  82.                    
  83.                     self.present(alertController, animated: true, completion: nil)
  84.                 }
  85.             }
  86.         }
  87.    
  88.     }
  89.    
  90.     //Facebook button functions
  91.     @IBAction func btnFBLoginPressed(_ sender: AnyObject) {
  92.         let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
  93.         fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) in
  94.             if (error == nil){
  95.                 let fbloginresult : FBSDKLoginManagerLoginResult = result!
  96.                 if fbloginresult.grantedPermissions != nil {
  97.                     if(fbloginresult.grantedPermissions.contains("email"))
  98.                     {
  99.                        
  100.                         self.getFBUserData()
  101.                         fbLoginManager.logOut()
  102.                     }
  103.                    
  104.                    
  105.                     //segue to next page after a succesfull facebook login
  106.                     DispatchQueue.main.asyncAfter(deadline: .now() + 0.4){
  107.                         self.performSegue(withIdentifier: "login", sender: self)
  108.                        
  109.                     }
  110.                        
  111.               //      DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
  112.               //          self.performSegue(withIdentifier: "login", sender: self)
  113.               //      }
  114.                    
  115.                    
  116.                 }
  117.             }
  118.         }
  119.     }
  120.    
  121.    
  122.    
  123.     //Facebook subfunction for getting and printing data to console
  124.     func getFBUserData(){
  125.         if((FBSDKAccessToken.current()) != nil){
  126.             FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
  127.                 if (error == nil){
  128.                     self.dict = result as! [String : AnyObject]
  129.                    
  130.                     //loggedIn Boolean
  131.                     defaults.set(true, forKey: "loggedIn")
  132.                    
  133.                     //Json parsed into global variables
  134.                     facebookdata = result as! [String : AnyObject]
  135.                     firstname = facebookdata["first_name"]! as! String
  136.                     lastname = facebookdata["last_name"]! as! String
  137.                     fbid = facebookdata["id"]! as! String
  138.                    
  139.                     print(result!)
  140.                     print(self.dict["first_name"]!)
  141.                     //  print(self.dict["id"]!)
  142.                     print(facebookdata["id"]!)
  143.                     //  print(self.dict["picture"]!)
  144.                 }
  145.             })
  146.         }
  147.     }
  148.    
  149.    
  150.    
  151.    
  152.     //Hide keyboard when user touches outside the keyboard
  153.     override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  154.         self.view.endEditing(true)
  155.     }
  156.    
  157.     //Return key press
  158.     func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  159.         textField.resignFirstResponder()
  160.         return (true)
  161.     }
  162.    
  163.    
  164.     //Unable login button if textfields are empty
  165.     func editingChanged(_ textField: UITextField) {
  166.         if textField.text?.characters.count == 1 {
  167.             if textField.text?.characters.first == " " {
  168.                 textField.text = ""
  169.                 return
  170.             }
  171.         }
  172.         guard
  173.             let username = usernameTextField.text, !username.isEmpty,
  174.             let password = userpasswordTextField.text, !password.isEmpty
  175.             else {
  176.                 loginButton.isEnabled = false
  177.                 return
  178.         }
  179.         loginButton.isEnabled = true
  180.     }
  181.    
  182.    
  183.    
  184. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top