如何仅在函数加载时显示警报? |斯威夫特

时间:2019-06-30 04:21:48

标签: ios swift

基本上,我具有以下JSON脚本来获取数据。我只想在FetchJSON加载数据时显示以下加载警报动画。

如何仅在FetchJSON加载所需的剩余时间内显示此加载警报。

正在加载警报代码:

    let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)

    let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
    loadingIndicator.hidesWhenStopped = true
    loadingIndicator.style = UIActivityIndicatorView.Style.gray
    loadingIndicator.startAnimating();

    alert.view.addSubview(loadingIndicator)
    present(alert, animated: true, completion: nil)

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 8.0) {
        self.dismiss(animated: false, completion: nil)

    }

获取JSON代码:

private func fetchJSON() {
    guard let url = URL(string: "https://example.com/example/example"),
        let value = driverName.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
        else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = "Name=\(value)".data(using: .utf8)

    URLSession.shared.dataTask(with: request) { data, _, error in
        guard let data = data else { return }


        do {
            self.structure = try JSONDecoder().decode([ScheduleStructure].self,from:data)
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
        catch {
            print(error)
        }

        }.resume()

}

1 个答案:

答案 0 :(得分:0)

您需要做的是声明一个实例变量来保存对UIAlertController的引用:

private var alert: UIAlertController?
func displayAlert() {
    let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)

    let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
    loadingIndicator.hidesWhenStopped = true
    loadingIndicator.style = UIActivityIndicatorView.Style.gray
    loadingIndicator.startAnimating();

    alert.view.addSubview(loadingIndicator)
    present(alert, animated: true, completion: nil)

    self.alert = alert
}

private func fetchJSON() {
    guard let url = URL(string: "https://example.com/example/example"),
        let value = driverName.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
        else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = "Name=\(value)".data(using: .utf8)

    URLSession.shared.dataTask(with: request) { data, _, error in
        guard let data = data else { return }

        do {
            self.structure = try JSONDecoder().decode([ScheduleStructure].self,from:data)
            DispatchQueue.main.async {
                self.tableView.reloadData()
                self.alert?.dismiss(animated: true) { self.alert?.view.removeFromSuperview() }
            }
        }
        catch {
            print(error)
        }
    }.resume()
}