Advertisement
Guest User

Untitled

a guest
Mar 3rd, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 7.21 KB | None | 0 0
  1. //
  2. //  ViewController.swift
  3. //  student-showcase
  4. //
  5. //  Created by Chris Augg on 1/18/16.
  6. //  Copyright © 2016 Auggie Doggie iOSware. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import Alamofire
  11. import Firebase
  12. import FBSDKCoreKit
  13. import FBSDKLoginKit
  14.  
  15. class LoginVC: UIViewController {
  16.  
  17.     @IBOutlet weak var emailField: UITextField!
  18.     @IBOutlet weak var passwordField: UITextField!
  19.    
  20.     var userHandle: UInt!
  21.     var currentUser: User!
  22.    
  23.    
  24.     override func viewDidLoad() {
  25.         super.viewDidLoad()
  26.        
  27.         }
  28.    
  29.     override func viewDidAppear(animated: Bool) {
  30.         super.viewDidAppear(animated)
  31.        
  32.         if let key = NSUserDefaults.standardUserDefaults().valueForKey(KEY_UID) {
  33.            
  34.             self.createCurrentUser(key as! String)
  35.         }
  36.     }
  37.    
  38.    
  39.     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  40.         if segue.identifier == "loggedIn" {
  41.            
  42.             let navController = segue.destinationViewController as! UINavigationController
  43.             let vc = navController.viewControllers.first as! FeedVC
  44.             vc.user = self.currentUser
  45.         } else if segue.identifier == "profile" {
  46.             let pvc = segue.destinationViewController as! ProfileVC
  47.             pvc.currentUser = self.currentUser
  48.         }
  49.     }
  50.  
  51.    
  52.    
  53.     @IBAction func fbBtnPressed(sender: UIButton!) {
  54.         let facebookLogin = FBSDKLoginManager()
  55.        
  56.         facebookLogin.logInWithReadPermissions(["email"], fromViewController: self, handler: { (facebookResult:FBSDKLoginManagerLoginResult!, facebookError: NSError!) -> Void in
  57.          
  58.             if facebookError != nil {
  59.                 print("Facebook login failed. Error \(facebookError)")
  60.             } else {
  61.                 let accessToken = FBSDKAccessToken.currentAccessToken().tokenString
  62.                 print("Successfully logged in with facebook. \(accessToken)")
  63.                
  64.                 DataService.ds.REF_BASE.authWithOAuthProvider("facebook", token: accessToken, withCompletionBlock: { error, authData in
  65.                
  66.                     if error != nil {
  67.                         print("Login Failed. \(error)")
  68.                     } else {
  69.                         print("Logged In!\(authData)")
  70.                        
  71.                         let user = ["provider": authData.provider!]
  72.                        
  73.                         DataService.ds.createFirebaseUser(authData.uid, user: user)
  74.                        
  75.                         NSUserDefaults.standardUserDefaults().setValue(authData.uid, forKey: KEY_UID)
  76.                         self.currentUser = User(userKey: authData.uid)
  77.                        
  78.                         self.performSegueWithIdentifier(SEGUE_PROFILE, sender: self.currentUser)
  79.                     }
  80.                
  81.                 })
  82.            
  83.             }
  84.         })
  85.     }
  86.    
  87.    
  88.     @IBAction func attemptLogin(sender: UIButton!) {
  89.        
  90.        
  91.        
  92.         if let email = emailField.text where email != "", let pwd = passwordField.text where pwd != "" {
  93.            
  94.            
  95.            
  96.             if ValidationService.vs.isEmailValid(email) && ValidationService.vs.isPasswordValid(pwd) {
  97.                
  98.                
  99.                 DataService.ds.REF_BASE.authUser(email, password: pwd, withCompletionBlock: {error, authData in
  100.                    
  101.                     if error != nil {
  102.                        
  103.                         if error.code == STATUS_ACCOUNT_NONEXIST {
  104.                            
  105.                             DataService.ds.REF_BASE.createUser(email, password: pwd, withValueCompletionBlock: { error, result in
  106.                                
  107.                                 if error != nil {
  108.                                     self.showErrorAlert("Could not create account", msg: "Problem creating account. Try something else")
  109.                                 } else {
  110.                                     NSUserDefaults.standardUserDefaults().setValue(result[KEY_UID], forKey: KEY_UID)
  111.                                    
  112.                                     DataService.ds.REF_BASE.authUser(email, password: pwd, withCompletionBlock: { error, authData in
  113.                                        
  114.                                         let aUser = ["provider": authData.provider!, "email": email]
  115.                                        
  116.                                         DataService.ds.createFirebaseUser(authData.uid, user: aUser)
  117.                                         self.currentUser = User(userKey: authData.uid)
  118.                                         self.performSegueWithIdentifier(SEGUE_PROFILE, sender: self.currentUser)
  119.                                        
  120.                                     })
  121.                                    
  122.                                 }
  123.                             })
  124.                            
  125.                         } else {
  126.                             self.showErrorAlert("Could not log in", msg: "Please check your user name or password")
  127.                         }
  128.                     } else {
  129.                         self.createCurrentUser(authData.uid)
  130.                     }
  131.                 })
  132.  
  133.             } else {
  134.                 showErrorAlert("Valid Email and Password Required", msg: INVALID_EMAIL_OR_PASSWORD())
  135.             }            
  136.            
  137.         } else {
  138.             showErrorAlert("Email and Password Required", msg: "You must enter an email and a password")
  139.         }
  140.     }
  141.    
  142.     func createCurrentUser(uid: String) {
  143.         let userRef = DataService.ds.REF_USERS
  144.        
  145.         userHandle = userRef.observeEventType(.Value, withBlock: { snapshot in
  146.            
  147.             if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
  148.                
  149.                 for snap in snapshots {
  150.                    
  151.                     let userDict = snap.value as! Dictionary<String, AnyObject>
  152.                     let key = snap.key
  153.                    
  154.                    
  155.                     if uid == key {
  156.                         if NSUserDefaults.standardUserDefaults().valueForKey(KEY_UID) != nil {
  157.                            
  158.                             self.currentUser = User(userKey: key, userHandle: self.userHandle, userDict: userDict)
  159.                         } else {
  160.                             NSUserDefaults.standardUserDefaults().setValue(key, forKey: KEY_UID)
  161.                             self.currentUser = User(userKey: key, userHandle: self.userHandle, userDict: userDict)
  162.                         }
  163.                         break
  164.                     }
  165.                 }
  166.             }
  167.            
  168.             self.performSegueWithIdentifier(SEGUE_LOGGED_IN, sender: self.currentUser)
  169.            
  170.         })
  171.     }
  172.    
  173.    
  174.     func showErrorAlert(title: String, msg: String) {
  175.        
  176.         let alert = UIAlertController(title: title, message: msg, preferredStyle: .Alert)
  177.         let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)        
  178.        
  179.         alert.addAction(action)
  180.         presentViewController(alert, animated: true, completion: nil)
  181.     }
  182. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement