带活动指示器的登录功能

时间:2017-05-05 05:07:52

标签: ios swift asynchronous login uiactivityindicatorview

我正在进行登录测试并且必须再次登录才能登录。按下登录按钮将请求发送到服务器后,活动指示器将显示在屏幕上,直到活动指示器停止并且活动指标停止了下一页,我想打开另一个用于实现活动指标的线程,但是我不知道如何实现,请大家帮忙! 此代码已从http://www.kaleidosblog.com/how-to-create-a-login-screen-page-in-swift-3-authenticate-an-user-and-keep-the-session-active修改。

    class ViewController: UIViewController {


    let login_url = "http://www.kaleidosblog.com/tutorial/login/api/Login"
    let checksession_url = "http://www.kaleidosblog.com/tutorial/login/api/CheckSession"


    @IBOutlet var username_input: UITextField!
    @IBOutlet var password_input: UITextField!
    @IBOutlet var login_button: UIButton!

    var login_session:String = ""

    var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)

    override func viewDidLoad() {
        super.viewDidLoad()


        username_input.text = "try@me.com"
        password_input.text = "test"

        activityIndicator.hidesWhenStopped = true;
        activityIndicator.activityIndicatorViewStyle  = UIActivityIndicatorViewStyle.gray;
        activityIndicator.center = view.center;


        let preferences = UserDefaults.standard
        if preferences.object(forKey: "session") != nil
        {
            login_session = preferences.object(forKey: "session") as! String
            check_session()
        }



    }

    @IBAction func DoLogin(_ sender: AnyObject) {

        login_now(username:username_input.text!, password: password_input.text!)
    }

    @IBAction func backToMain(_ segue:UIStoryboardSegue){
        let preferences = UserDefaults.standard
        preferences.removeObject(forKey: "session")
        self.dismiss(animated: true, completion: nil)

    }


    func login_now(username:String, password:String)
    {
        let post_data: NSDictionary = NSMutableDictionary()


        post_data.setValue(username, forKey: "username")
        post_data.setValue(password, forKey: "password")

        let url:URL = URL(string: login_url)!
        let session = URLSession.shared

        let request = NSMutableURLRequest(url: url)
        request.httpMethod = "POST"
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

        var paramString = ""


        for (key, value) in post_data
        {
            paramString = paramString + (key as! String) + "=" + (value as! String) + "&"
        }

        request.httpBody = paramString.data(using: String.Encoding.utf8)

        let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (
            data, response, error) in

            guard let _:Data = data, let _:URLResponse = response  , error == nil else {

                return
            }

            let json: Any?

            do
            {
                json = try JSONSerialization.jsonObject(with: data!, options: [])
            }
            catch
            {
                return
            }

            guard let server_response = json as? NSDictionary else
            {
                return
            }


            if let data_block = server_response["data"] as? NSDictionary
            {
                if let session_data = data_block["session"] as? String
                {
                    self.login_session = session_data

                    let preferences = UserDefaults.standard
                    preferences.set(session_data, forKey: "session")
                    DispatchQueue.main.async {
                        self.view.addSubview(self.activityIndicator)
                    }

                }
            }
        })

        task.resume()
        LoginDone()


    }

    func check_session()
    {
        let post_data: NSDictionary = NSMutableDictionary()


        post_data.setValue(login_session, forKey: "session")

        let url:URL = URL(string: checksession_url)!
        let session = URLSession.shared

        let request = NSMutableURLRequest(url: url)
        request.httpMethod = "POST"
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

        var paramString = ""


        for (key, value) in post_data
        {
            paramString = paramString + (key as! String) + "=" + (value as! String) + "&"
        }

        request.httpBody = paramString.data(using: String.Encoding.utf8)

        let task = session.dataTask(with: request as URLRequest, completionHandler: {
            (
            data, response, error) in

            guard let _:Data = data, let _:URLResponse = response  , error == nil else {

                return
            }


            let json: Any?

            do
            {
                json = try JSONSerialization.jsonObject(with: data!, options: [])
            }
            catch
            {
                return
            }

            guard let server_response = json as? NSDictionary else
            {
                return
            }

            if let response_code = server_response["response_code"] as? Int
            {
                if(response_code == 200)
                {
                    DispatchQueue.main.async {
                        self.view.addSubview(self.activityIndicator)
                    }
                }
                else
                {

                }
            }



        })

        task.resume()
    }

    func LoginDone()
    {
        self.performSegue(withIdentifier: "gotomenu", sender: nil)
    }


    func startActivityIndicator(){
        activityIndicator.startAnimating()
    }

    func stopActivityIndicator() {
        activityIndicator.stopAnimating()
    }


}

2 个答案:

答案 0 :(得分:3)

尝试使用SVProgressHUD。这是我见过的最简单的框架。 SVProgressHUD on GitHub

安装:

在你的podfile中:

pod 'SVProgressHUD'

然后在终端:

pod install

使用方法:

import SVProgressHUD

开始:

SVProgressHUD.show()

解雇:

SVProgressHUD.dismiss()

它非常简单有用。试试吧。

希望有所帮助

答案 1 :(得分:2)

用旧代码替换此代码:

class ViewController: UIViewController {


let login_url = "http://www.kaleidosblog.com/tutorial/login/api/Login"
let checksession_url = "http://www.kaleidosblog.com/tutorial/login/api/CheckSession"


@IBOutlet var username_input: UITextField!
@IBOutlet var password_input: UITextField!
@IBOutlet var login_button: UIButton!

var login_session:String = ""

var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)

override func viewDidLoad() {
    super.viewDidLoad()


    username_input.text = "try@me.com"
    password_input.text = "test"

    activityIndicator.hidesWhenStopped = true
    activityIndicator.activityIndicatorViewStyle  = UIActivityIndicatorViewStyle.gray
    activityIndicator.center = view.center
    activityIndicator.isHidden = true
    self.view.addSubview(self.activityIndicator)
    let preferences = UserDefaults.standard
    if preferences.object(forKey: "session") != nil
    {
        login_session = preferences.object(forKey: "session") as! String
        check_session()
    }



}

@IBAction func DoLogin(_ sender: AnyObject) {

    login_now(username:username_input.text!, password: password_input.text!)
}

@IBAction func backToMain(_ segue:UIStoryboardSegue){
    startActivityIndicator()
    activityIndicator.isHidden = false
    let preferences = UserDefaults.standard
    preferences.removeObject(forKey: "session")
    self.dismiss(animated: true, completion: nil)
    stopActivityIndicator()
    activityIndicator.isHidden = true
}


func login_now(username:String, password:String)
{
    activityIndicator.isHidden = false
    startActivityIndicator()
    let post_data: NSDictionary = NSMutableDictionary()


    post_data.setValue(username, forKey: "username")
    post_data.setValue(password, forKey: "password")

    let url:URL = URL(string: login_url)!
    let session = URLSession.shared

    let request = NSMutableURLRequest(url: url)
    request.httpMethod = "POST"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

    var paramString = ""


    for (key, value) in post_data
    {
        paramString = paramString + (key as! String) + "=" + (value as! String) + "&"
    }

    request.httpBody = paramString.data(using: String.Encoding.utf8)

    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (
        data, response, error) in
        self.stopActivityIndicator()
        self.activityIndicator.isHidden = true
        guard let _:Data = data, let _:URLResponse = response  , error == nil else {

            return
        }

        let json: Any?

        do
        {
            json = try JSONSerialization.jsonObject(with: data!, options: [])
        }
        catch
        {
            return
        }

        guard let server_response = json as? NSDictionary else
        {
            return
        }


        if let data_block = server_response["data"] as? NSDictionary
        {
            if let session_data = data_block["session"] as? String
            {
                self.login_session = session_data

                let preferences = UserDefaults.standard
                preferences.set(session_data, forKey: "session")
                DispatchQueue.main.async {
                    self.LoginDone()
                }

            }
        }
    })

    task.resume()



}

func check_session()
{
    let post_data: NSDictionary = NSMutableDictionary()


    post_data.setValue(login_session, forKey: "session")

    let url:URL = URL(string: checksession_url)!
    let session = URLSession.shared

    let request = NSMutableURLRequest(url: url)
    request.httpMethod = "POST"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

    var paramString = ""


    for (key, value) in post_data
    {
        paramString = paramString + (key as! String) + "=" + (value as! String) + "&"
    }

    request.httpBody = paramString.data(using: String.Encoding.utf8)

    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (
        data, response, error) in

        guard let _:Data = data, let _:URLResponse = response  , error == nil else {

            return
        }


        let json: Any?

        do
        {
            json = try JSONSerialization.jsonObject(with: data!, options: [])
        }
        catch
        {
            return
        }

        guard let server_response = json as? NSDictionary else
        {
            return
        }

        if let response_code = server_response["response_code"] as? Int
        {
            if(response_code == 200)
            {
                DispatchQueue.main.async {
                    self.view.addSubview(self.activityIndicator)
                }
            }
            else
            {

            }
        }



    })

    task.resume()
}

func LoginDone()
{
    self.performSegue(withIdentifier: "gotomenu", sender: nil)
}


func startActivityIndicator(){
    activityIndicator.startAnimating()
}

func stopActivityIndicator() {
    activityIndicator.stopAnimating()
}
}