Search code examples
iosswiftuiactivityindicatorview

Loading activity indicator for display during async request


I have been trying to implement code that will display a activity indicator in a sub view during a request. It's meant to be used for loading, however it never displays yet if I go to another segue and then return back the indicator is now there. This makes me believe the superview doesn't get reloaded until my function has run by which time the sub view doesn't need to be displayed

Example:

loadingIndicator.startIndicator(self.view)

        let parameters = Parameters()

        parameters.addParams(search: search)
        let request = SearchRQ(parameters: parameters)

        request.getResponse()

        while !request.isComplete
        {
            //Wait
        }

        let results = request.parseResponse()
        self.results = results

        loadingIndicator.stopIndicator(self.view)

        performSegueWithIdentifier("showSearchResults", sender: sender)

Solution

  • As matt stated, you need to add your activity indicator to the view (or any UI changes for that matter) on the main thread.

    You can do that like so:

    dispatch_async(dispatch_get_main_queue(),{
        self.view.addSubview(activityIndicator)
    })
    

    To move waiting for your response OFF the main thread, change your getResponse function so that it has a completion handler. :

    func getResponse(responseReceived:() ->Void) {
        // Once I get my response:
        responseReceived()
    }
    

    Then you can do the appropriate changes after you've received the response.

    getResponse {
        let results = request.parseResponse()
        self.results = results
    
        loadingIndicator.stopIndicator(self.view)
    
        performSegueWithIdentifier("showSearchResults", sender: sender)
    }