Advertisement
Guest User

Untitled

a guest
May 10th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.00 KB | None | 0 0
  1. import Foundation
  2. import Alamofire
  3.  
  4.  
  5. class User {
  6.    
  7.    
  8.     let defaults = UserDefaults.standard
  9.    
  10.     var email: String
  11.     var password: String
  12.     var isLoggedIn: Bool
  13.    
  14.     init(email: String, password: String) {
  15.         self.email = email
  16.         self.password = password
  17.         self.isLoggedIn = false
  18.     }
  19.    
  20.     // Perform authentication
  21.     func authenticateUser(user: User, completionHandler: @escaping (_ result: Bool) -> ()) {
  22.         makeAuthenticateUserCall(user: user, completionHandler: completionHandler)
  23.     }
  24.    
  25.     // Perform POST request
  26.     func makeAuthenticateUserCall(user: User, completionHandler: @escaping (Bool) -> ()) {
  27.  
  28.         let parameters = [
  29.             "email" : user.email,
  30.             "password" : user.password
  31.         ]
  32.        
  33.         Alamofire.request("http://apistaging.server.com/api/v1/login", method: .post, parameters: parameters, encoding:  URLEncoding.httpBody).responseJSON {response in
  34.                
  35.                 switch response.result {
  36.                 case .success:
  37.                     if let json = response.result.value as? [String: Any],
  38.                         let status = json["status"] as? String,
  39.                         status == "success" {
  40.                         completionHandler(true)
  41.                     }
  42.                 case .failure:
  43.                     completionHandler(false)
  44.                 }
  45.         }
  46.     }
  47. }
  48.  
  49. // Код из ViewController:
  50.  
  51.     @IBAction func loginButtonPressed(_ sender: UIButton) {
  52.        
  53.         if let email = _email.text {
  54.             if let password = _password.text {
  55.                 let user = User(email: email, password: password)
  56.                 user.authenticateUser(user: user) {resultBool in
  57.                         user.isLoggedIn = resultBool
  58.                     }
  59.                 if user.isLoggedIn {
  60.                     self.performSegue(withIdentifier: "MainPageViewController", sender: nil)
  61.                 }
  62.             }
  63.         }
  64.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement