LoginViewController.swift 7.01 KB
//
//  LoginViewController.swift
//  YouerLiveVideo
//
//  Created by 左丞 on 16/11/11.
//  Copyright © 2016年 左丞. All rights reserved.
//

import UIKit

class LoginViewController: UIViewController,UITextFieldDelegate {
    @IBOutlet var changeViewTop: NSLayoutConstraint!
    @IBOutlet var phoneNumberTextField: UITextField!
    @IBOutlet var passwordTextField: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        let numberPlaceholder=NSMutableAttributedString(string: "请输入11位数的手机号码")
        numberPlaceholder.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSMakeRange(0, 12))
        phoneNumberTextField.attributedPlaceholder=numberPlaceholder
        phoneNumberTextField.tintColor=Theme.topBarColor()
        let passwordPlaceholder=NSMutableAttributedString(string: "请输入6位以上的密码")
        passwordPlaceholder.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSMakeRange(0, 10))
        passwordTextField.attributedPlaceholder=passwordPlaceholder
        passwordTextField.tintColor=Theme.topBarColor()
        
        NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.refreshUser), name: NSNotification.Name(rawValue: "refreshLoginUser"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.keyboardWIllChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
//        let leftbtn = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(LoginViewController.back))
//        self.navigationItem.title = "登录"
//        self.navigationItem.leftBarButtonItem = leftbtn
        changeViewTop.constant=(getScreenHeight()-64-220)/2
    }
    //点击页面回收键盘
    @IBAction func touchAction(_ sender: AnyObject) {
        self.view.endEditing(true)//回收键盘
    }
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return UIStatusBarStyle.lightContent
    }
    //输入密码点击return回收键盘
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    //注册完了后自动填充账号
    func refreshUser(noti:Notification){
        phoneNumberTextField.text = "\(noti.object!)"
    }
    //点击登录按钮
    @IBAction func loginBtnClickAction(_ sender: Any) {
        self.view.endEditing(true)
        if phoneNumberTextField.text!.isMobilePhoneNumber() {
            SVProgressHUD.show(withStatus: "登录...")
            SVProgressHUD.setDefaultMaskType(.black)
            let parameters:Dictionary<String,AnyObject>=["grant_type":"password" as AnyObject,"username":phoneNumberTextField.text! as AnyObject,"password":passwordTextField.text! as AnyObject]
            AppDelegate.instance().httpServer.login(parameters: parameters) { (str, error) in
                let json=JSON.fromString(jsonString: str)
                if let ret=json{
                    let er=ret["error"].string
                    if let errorStr=er{
                        SVProgressHUD.dismiss()
                        let Strings=errorStr.components(separatedBy:":")
                        if Strings.count >= 2 {
                            switch Strings[1] {
                            //用户关联多个身份,请使用学事号登录:100
                            case "101"://用户认证身份不存在:101
                                AppDelegate.instance().window?.makeToast("用户认证身份不存在,请进行账号激活。")
                                break
                            //用户帐号或密码错误:102
                            case "103":// 用户不存在:103
                                AppDelegate.instance().window?.makeToast("该号码不存在,请联系客服400-826-2468")
                                break
                            default:
                                AppDelegate.instance().window?.makeToast("\(errorStr)")
                                break
                            }
                        }else{
                            AppDelegate.instance().window?.makeToast("\(errorStr)")
                        }
                    }else if ret["access_token"].stringValue != ""{
                        AppDelegate.instance().accountManager.setTokenInfo(tokenInfo: ret)
                        AppDelegate.instance().accountManager.saveToken(tokenInfo: ret)
                        AppDelegate.instance().accountManager.refreshUserInfo(completionHandler: { (finish) in
                            if finish{
//                                self.loadUserInfo()
                                SVProgressHUD.dismiss()
                                self.back()
                            }else{
                                AppDelegate.instance().window?.makeToast("身份获取失败")
                                SVProgressHUD.dismiss()
                            }
                        })
                    }else{
                        SVProgressHUD.dismiss()
                        AppDelegate.instance().window?.makeToast("登录失败,请稍后重试")
                    }
                }else{
                    SVProgressHUD.dismiss()
                    AppDelegate.instance().window?.makeToast("登录失败")
                }
            }
        }else{
            self.view.makeToast("请输入正确手机号")
        }
    }
    func loadUserInfo(){
        XSTLiveManager.shareXSTLiveManager().login(userId: self.phoneNumberTextField.text!, completion: { (success) in
            if !success{
                AppDelegate.instance().window?.makeToast("聊天服务登录失败,请连接网络重试")
                SVProgressHUD.dismiss()
            }else{
                SVProgressHUD.dismiss()
                self.back()
            }
        })
    }
    func back(){
        self.dismiss(animated: true, completion: nil)
        LeadViewController.instance.removeAll()
        LeadViewController.instance.showMain()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //点击注册按钮
    @IBAction func registerBtnClickAction(_ sender: AnyObject) {
        let vc = UIStoryboard(name: "User", bundle: nil).instantiateViewController(withIdentifier: "RegisterViewControllerNV")
        self.present(vc, animated: true, completion: nil)
    }
    //键盘监听
    func keyboardWIllChange(noti: NSNotification){
        let userInfo:NSDictionary=noti.userInfo! as NSDictionary
        let endFrame=(userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
        if endFrame?.origin.y==getScreenHeight() {
            changeViewTop.constant=(getScreenHeight()-64-220)/2
        }else{
            let y = (getScreenHeight()-64-220)/2+CGFloat(64+220)
            if (endFrame?.origin.y)! < y {
                changeViewTop.constant=getScreenHeight()-64-(endFrame?.size.height)!-220
            }
        }
    }

}