gpt4 book ai didi

ios - 如何仅在函数加载时显示警报? | swift

转载 作者:行者123 更新时间:2023-11-28 07:25:08 24 4
gpt4 key购买 nike

基本上我有以下获取数据的 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)

}

FetchJSON 代码:

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

}

最佳答案

您只需声明一个实例变量来保存对 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()
}

关于ios - 如何仅在函数加载时显示警报? | swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56822361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com