Habber - IOS XMPP 客户端 教程 (三)VC始于LoginViewController、、

VC始于登录页面

之所以用了这个标题因为app结构不大又把view和controller写在了一起。。。。。不过我已经用 //MARK: 标注了应该会清晰一些。

好吧,先不管其它,的确是从swift版的登录页面开始。
这里已经认为你做好了storyboard上带server文本框的界面,上代码!

LoginViewController.swift

//
//  LoginViewController.swift
//  Habber
//
//  Created by Sunny on 12/15/15.
//  Copyright © 2015 Nine. All rights reserved.
//

import UIKit

class LoginViewController: UIViewController, UITextFieldDelegate {


    //MARK: Outlets for UI Elements.
    @IBOutlet weak var usernameField:   UITextField!
    @IBOutlet weak var imageView:       UIImageView!
    @IBOutlet weak var passwordField:   UITextField!
    @IBOutlet weak var serverField:     UITextField!
    @IBOutlet weak var loginButton:     UIButton!

    //新增的登录旋转小菊花状态指示
    private let indicator = UIActivityIndicatorView()

    private let friendListTableViewController = FriendListTableViewController()
    //MARK: Global Variables for Changing Image Functionality.
    private var idx: Int = 0
    private let backGroundArray = [UIImage(named: "img1.jpg"),UIImage(named:"img2.jpg"), UIImage(named: "img3.jpg"), UIImage(named: "img4.jpg")]

    //MARK: View Controller LifeCycle
    override func viewDidLoad() {
        super.viewDidLoad()

        usernameField.delegate = self
        passwordField.delegate = self
        serverField.delegate = self

        usernameField.alpha = 0;
        passwordField.alpha = 0;
        loginButton.alpha   = 0;
        serverField.alpha = 0;

        //作者写的动态效果
        UIView.animateWithDuration(0.7, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
            self.usernameField.alpha = 1.0
            self.passwordField.alpha = 1.0
            self.serverField.alpha = 1.0
            self.loginButton.alpha   = 0.9
            }, completion: nil)

        // Notifiying for Changes in the textFields
        usernameField.addTarget(self, action: "textFieldDidChange", forControlEvents: UIControlEvents.EditingChanged)
        passwordField.addTarget(self, action: "textFieldDidChange", forControlEvents: UIControlEvents.EditingChanged)
        serverField.addTarget(self, action: "textFieldDidChange", forControlEvents: UIControlEvents.EditingChanged)


        // Visual Effect View for background
        let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Dark)) as UIVisualEffectView
        visualEffectView.frame = self.view.frame
        visualEffectView.alpha = 0.5
        imageView.image = UIImage(named: "img1.jpg")
        imageView.addSubview(visualEffectView)

        NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "changeImage", userInfo: nil, repeats: true)
        self.loginButton(false)

        //这里用手写添加活动指示器,练练手写UI、、
        indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
        indicator.center = CGPointMake(loginButton.bounds.size.width/2, loginButton.bounds.size.height/2)
        loginButton.addSubview(indicator)
        indicator.hidden = true

    }

    override func viewDidAppear(animated: Bool) {
        //监听
        //登录服务器失败,弹出警示框
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "connectServerFailed", name: "connectServerFailed", object: nil)
        //认证成功,就可以跳转了
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "hasAuthenticated", name: "hasAuthenticated", object: nil)
        //认证失败,弹出警示框
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "authenticateFail", name: "authenticateFail", object: nil)

        //自动填写文本框
        let defaults = NSUserDefaults.standardUserDefaults();
        if (defaults.objectForKey(USERID) != nil && defaults.objectForKey(PASS) != nil) {
            usernameField.text = String(defaults.objectForKey(USERID)!)
            passwordField.text = String(defaults.objectForKey(PASS)!)
            //在button上面加个活动指示器
            self.loginButton(true)
        }
        if (defaults.objectForKey(SERVER) != nil) {
            serverField.text = String(defaults.objectForKey(SERVER)!)
        }
        indicatorStop()
    }

    //控制小菊花的功能块
    func indicatorStop() {
        indicator.stopAnimating()
        indicator.hidden = true
        loginButton.setTitle("Login", forState: UIControlState.Normal)
    }

    func indicatorStart() {
        indicator.hidden = false
        loginButton.setTitle("", forState: UIControlState.Normal)
        indicator.startAnimating()
    }

    //MARK: - 通知的selector实现
    func connectServerFailed() {
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            let alert = UIAlertView()
            alert.title = "Connection failed!"
            alert.delegate = nil
            alert.message = "Could not connect to server."
            alert.addButtonWithTitle("OK")
            alert.show()
            self.indicatorStop()
        }
    }

    func authenticateFail() {
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            let alert = UIAlertView()
            alert.title = "Login failed!"
            alert.delegate = nil
            alert.message = "Wrong username or password"
            alert.addButtonWithTitle("OK")
            alert.show()
            self.indicatorStop()
        }
    }

    func hasAuthenticated() {
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            NSNotificationCenter.defaultCenter().removeObserver(self)
            self.indicatorStop()
            self.performSegueWithIdentifier("login", sender: nil)
        }
    }

    //MARK: - 实现UITextFieldDelegate
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        if (textField == usernameField || textField == passwordField || textField == serverField) {
            textField.resignFirstResponder()
        }
        return true
    }

    //MARK: - 获得xmppStream
    func getAppDelegate() -> AppDelegate {
        return UIApplication.sharedApplication().delegate as! AppDelegate
    }

    func xmppStream() -> XMPPStream {
        return self.getAppDelegate().xmppStream
    }
    //MARK: -

    //原作者写的login button动态效果
    func loginButton(enabled: Bool) -> () {
        func enable(){
            UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
                self.loginButton.backgroundColor = UIColor.colorWithHex("#33CC00", alpha: 1)
                }, completion: nil)
            loginButton.enabled = true
        }
        func disable(){
            loginButton.enabled = false
            UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
                self.loginButton.backgroundColor = UIColor.colorWithHex("#333333",alpha :1)
                }, completion: nil)
        }
        return enabled ? enable() : disable()
    }

    func changeImage(){
        if idx == backGroundArray.count-1{
            idx = 0
        }
        else{
            idx++
        }
        let toImage = backGroundArray[idx];
        UIView.transitionWithView(self.imageView, duration: 3, options: .TransitionCrossDissolve, animations: {self.imageView.image = toImage}, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    //这里不打算加上server,server默认localhost
    func textFieldDidChange() {
        if usernameField.text!.isEmpty || passwordField.text!.isEmpty
        {
            self.loginButton(false)
        }
        else
        {
            self.loginButton(true)
        }
    }

    //MARK: - 按钮按下
    @IBAction func loginPressed(sender: UIButton) {
        let defaults = NSUserDefaults.standardUserDefaults();
        defaults.setObject(usernameField.text, forKey: USERID)
        defaults.setObject(passwordField.text, forKey: PASS)
        if (!serverField.text!.isEqual("")) {
            defaults.setObject(serverField.text, forKey: SERVER)
        } else {
            defaults.setObject("localhost", forKey: SERVER)
        }
        //把登录用户数据保存到数据库
        defaults.synchronize()

        indicatorStart()

        self.getAppDelegate().disconnect()
        self.getAppDelegate().connect()

        usernameField.resignFirstResponder()
        passwordField.resignFirstResponder()
        serverField.resignFirstResponder()

    }
    //MARK: -

    //这里可以给一个注册的页面,添加一个注册的功能,我没有写、那就同步一下数据库吧。
    @IBAction func signupPressed(sender: AnyObject) {
        NSUserDefaults.standardUserDefaults().synchronize()
    }


    @IBAction func backgroundPressed(sender: AnyObject) {
        usernameField.resignFirstResponder()
        passwordField.resignFirstResponder()
        serverField.resignFirstResponder()
    }

    //MARK: - 执行Segue
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "login") {
            let friendListTVC = (segue.destinationViewController as! UINavigationController).topViewController as! FriendListTableViewController
            friendListTVC.loginFlag = "success"
        }
    }
    //MARK: -

}

//Extension for Color to take Hex Values
extension UIColor{

    class func colorWithHex(hex: String, alpha: CGFloat = 1.0) -> UIColor {
        var rgb: CUnsignedInt = 0;
        let scanner = NSScanner(string: hex)

        if hex.hasPrefix("#") {
            // skip '#' character
            scanner.scanLocation = 1
        }
        scanner.scanHexInt(&rgb)

        let r = CGFloat((rgb & 0xFF0000) >> 16) / 255.0
        let g = CGFloat((rgb & 0xFF00) >> 8) / 255.0
        let b = CGFloat(rgb & 0xFF) / 255.0

        return UIColor(red: r, green: g, blue: b, alpha: alpha)
    }

}

重新给代码添加了些注释放了上来,
这里主要添加了:

  • 对AppDelegate的通知监听,并以UIAlertView的方式进行弹出提示。
  • 登录过以后,自动填写用户名密码服务器
  • login 按下后功能的封装

    除了JamalK添加的动态效果外,我自己又添加了一个登录button上旋转菊花指示器,丝毫不毁界面的美观性 ^_^ (I ignore here what you say ) ~~
    

兼容桥文件的内容

Habber-Bridging-Header.h

#import "FriendListTableViewController.h"
#import "Statics.h"
#import "AppDelegate.h"

P.S. 如果对swift和OC兼容不太了解可以看这篇文章:
在项目里交叉使用Swift和OC

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值