【问题标题】:UIActivityIndicatorView not showing before the URLSession.shared.dataTaskUIActivityIndi​​catorView 未在 URLSession.shared.dataTask 之前显示
【发布时间】:2020-03-18 07:03:49
【问题描述】:

当我在 API 请求之前调用它时,我的 UIActivityIndi​​catorView 不显示,并在请求完成后显示,

这是我在按钮的TouchUpInside 内运行的函数

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)
    }
}

我的请求代码是

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
}

当我在 onLogin() 函数中删除 do catchgetData() 时,UIActivityIndi​​catorView 运行良好。

我的 API 调用的响应是请求超时,但我想查看加载请求的指示器。

【问题讨论】:

  • 尝试在DispatchQueue.main.async {}中使用您的活动指示器
  • @EmreDeğirmenci 我没有将 activityIndi​​cator 放在 DispatchQueue.main.async {} 中,而是将 do {} catch {} 用它包裹起来并工作,因为当我用它包裹 activityIndicator 时,它仍然没有显示, 这样好吗?或者有什么我错过了或者不是一个好的做法?
  • 我对好的做法一无所知。

标签: swift uiactivityindicatorview


【解决方案1】:

尝试将活动指示器带到 UIview 的前面并在 DispatchQueue.main.async 中使用它

【讨论】:

  • 我没有把 activityIndi​​cator 放在 DispatchQueue.main.async {} 中,而是用它包裹我的 do {} catch {} 并工作,因为当我用它包裹我的 activityIndicator 时,它仍然没有显示,是可以吗?或者有什么我错过了或者不是一个好的做法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多