HiveBrain v1.2.0
Get Started
← Back to all entries
patternswiftMinor

Showing activity indicator (loading image) while processing in background

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
imageshowingwhilebackgroundloadingindicatoractivityprocessing

Problem

I have a login screen on my iOS app. When I click login button I want to make sure that user should be displayed a loading image in center of the screen.

I found lots of different methods online but I am after a simplest method. I found a way to display activity Indicator with minimum code:

First of all, import your UI Kit:

import UIKit;


Then you have to initiate activity indicator:

let activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView();


Then just copy paste this functions below which are self explainatory and call them whereever you need them:

func startLoading(){
    activityIndicator.center = self.view.center;
    activityIndicator.hidesWhenStopped = true;
    activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray;
    view.addSubview(activityIndicator);

    activityIndicator.startAnimating();
    UIApplication.shared.beginIgnoringInteractionEvents();

}

func stopLoading(){ 

    activityIndicator.stopAnimating();
    UIApplication.shared.endIgnoringInteractionEvents();

}


Although, I am still not convinced that it's the best way to do it. Could it still be reduced?

Here is how my screen looks with the code:

Solution

There are a few things I would recommend to do.

-
Usually, instead of disabling the interaction events there is an extra layer on top of all views that contains the activity indicator. So, instead of adding the activity indicator directly into the viewController's view, add it in another view first with clear background color and with 0.4 alpha.

-
Right now the startLoading() function also sets up the activity indicator, what i would rather separate into a different function, like setupLoading()

-
If you want to reuse the solution on other viewControllers, create a class or a protocol at least ecapsulating the logic. Also, it is better to present it on the UIApplication's keyWindow property, than just simply adding it to viewContollers view's.

-
Prepare for the stopLoading() and startLoading() functions to be called from a background thread.

Finally, there are plenty of very good solutions already on the interwebs, that you could integrate into your project, like SwiftSpinner.

If you need further help, code examples, let me know and I will edit my answer.

Context

StackExchange Code Review Q#150300, answer score: 2

Revisions (0)

No revisions yet.