我有一个带有单个textView的视图控制器,我从服务器获取一个字符串并在其上进行设置。
我在 viewDidAppear 中调用了http-get服务,我需要显示一个弹出警报,以等待用户获取字符串
我已尽一切努力,但无法在加载警报时关闭popalert和应用程序堆栈
override func viewWillAppear(_ animated: Bool) {
fetchAndPrintEachPerson()
networkReachablity()
popUpLoading() // start showing loading pop alert
getPerson ()
}
override func viewDidLoad() {
super.viewDidLoad()
style()
giftTextFiled.isEnabled = false
}
func popUpLoading(){
popUpAlert = UIAlertController(title: nil, message: "wait ...", preferredStyle: .alert)
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
loadingIndicator.startAnimating();
popUpAlert.view.addSubview(loadingIndicator)
present(popUpAlert, animated: true, completion: nil)
}
func getPerson(){
guard let url=URL(string: "\(address)person/code") else {return}
print(url)
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let res=response {
//print(res)
}
do {
if let dataContent=data {
let con = try? JSONSerialization.jsonObject(with: dataContent, options: []) as? AnyObject
let data = con??["data"] as? AnyObject
let code = data?["code"] as? String
print(code)
// self.popUpAlert.dismiss(animated: true, completion: {
DispatchQueue.main.async(execute: {
//self.giftTextFiled.text=code!
self.giftTextFiled.isEnabled = true
self.popUpAlert.dismiss(animated: true, completion: nil)
})
//})
}else {
let snack=snackBarAlert()
snack.alert(title: "error", color: UIColor.red)
self.popUpAlert.dismiss(animated: true, completion: nil)
}
}catch let err{
print(err)
DispatchQueue.main.async(execute: {
self.popUpAlert.dismiss(animated: true, completion: nil)
})
}
}.resume()
}
更新第一篇文章。
答案 0 :(得分:0)
尝试将其放入DidLoad视图中,并检查是否从服务器获得了响应,否则它将通过else块掉落并继续显示弹出窗口
答案 1 :(得分:0)
URLSession.shared.dataTask
完成关闭,这可能会为UI产生意外的结果。将您的UI代码分配到主线程。
URLSession.shared.dataTask(with: url) { (data, response, error) in
DispatchQueue.main.async {
// Your UI related code
}
}.resume()