0
votes

My UIActivityIndicatorView is not showing when I call it before the API request, and will show after the request has been done,

This is my function that run inside the TouchUpInside of my button

func onLogin () {
    let activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
    activityIndicator.center = view.center
    activityIndicator.hidesWhenStopped = true
    activityIndicator.style = UIActivityIndicatorView.Style.gray
    view.addSubview(activityIndicator)

    activityIndicator.startAnimating()

    do {
        let data = try self.getData()
        let loginData = try JSONDecoder().decode(LoginResponse.self, from: data!)
        print(loginData)
    } catch {
        let alert = UIAlertController(title: "Login failed", message: nil, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true, completion: nil)
    }
}

and my request code was

static func getData() throws -> Data? {
    let urlData = URL(string: "www.example.com")
    var request : URLRequest = URLRequest(url: urlData!)
    request.httpMethod = "POST"

    request.httpBody = self.getBodyString.data(using: .utf8)

    var data: Data?
    var response: URLResponse?
    var error: Error?

    let semaphore = DispatchSemaphore(value: 0)

    URLSession.shared.dataTask(with: request) { d,r,e in
        data = d
        response = r
        error = e

        semaphore.signal()
    }.resume()

    _ = semaphore.wait(timeout: .distantFuture)

    if error != nil {
        throw error!
    }

    return data
}

when I remove the do catch with getData() in my onLogin() function the UIActivityIndicatorView was working good.

The response of my API call was request timeout, but I want to see the indicator loading the request.

1
Try to use your activity indicator in DispatchQueue.main.async {} - Emre Değirmenci
@EmreDeğirmenci I didn't put the activityIndicator in the DispatchQueue.main.async {} instead, I wrap my do {} catch {} with it and worked, because when I wrapped my activityIndicator with it, it's still not showing, is that alright? or there's something i missed or not a good practice? - Dylan
I do not have any idea about good practice or not. - Emre Değirmenci

1 Answers

0
votes

Try to bring activity indictor to front of UIview and Use it in DispatchQueue.main.async