Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading Indicator in Swift

How can display a loading indicator in an view controller.

I am using Alamofire in viewDidLoad() ....

    Alamofire.request(.GET, formURL, parameters: nil)
        .responseJSON { (request, response, jsonResult, error) in


            }
like image 236
Gilberto Ibarra Avatar asked Mar 10 '15 08:03

Gilberto Ibarra


People also ask

What is UIActivityIndicatorView?

A view that shows that a task is in progress.


1 Answers

There is more than one way to do that but if you call the Alamofire in view controller you can add those properties to the class:

var spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
var loadingView: UIView = UIView()

And add two helpers, you should customise is to whatever fit right in your app:

func showActivityIndicator() {
    dispatch_async(dispatch_get_main_queue()) {
        self.loadingView = UIView()
        self.loadingView.frame = CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)
        self.loadingView.center = self.view.center
        self.loadingView.backgroundColor = UIColor(rgba: "#444444")
        self.loadingView.alpha = 0.7
        self.loadingView.clipsToBounds = true
        self.loadingView.layer.cornerRadius = 10

        self.spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
        self.spinner.frame = CGRect(x: 0.0, y: 0.0, width: 80.0, height: 80.0)
        self.spinner.center = CGPoint(x:self.loadingView.bounds.size.width / 2, y:self.loadingView.bounds.size.height / 2)

        self.loadingView.addSubview(self.spinner)
        self.view.addSubview(self.loadingView)
        self.spinner.startAnimating()
    }
}

func hideActivityIndicator() {
    dispatch_async(dispatch_get_main_queue()) {
        self.spinner.stopAnimating()
        self.loadingView.removeFromSuperview()
    }
}

And call it when you need, for example:

showActivityIndicator()
Alamofire.request(.GET, formURL, parameters: nil)
        .responseJSON { (request, response, jsonResult, error) in
             self.hideActivityIndicator()

            }
like image 167
Greg Avatar answered Sep 19 '22 01:09

Greg