gpt4 book ai didi

ios - 异步 Web 请求后无法让事件指示器停止

转载 作者:行者123 更新时间:2023-11-30 12:32:05 25 4
gpt4 key购买 nike

我需要事件指示器在发出网络请求时启动并在完成后停止。现在指示器将显示,但 .stopAnimation 甚至立即执行,而不等待 Web 请求完成。

import UIKit


class ViewController:
UIViewController,UIPickerViewDelegate,UIPickerViewDataSource {

@IBOutlet weak var locationPickerOutlet: UIPickerView!
@IBOutlet weak var theProgressOutlet: UIActivityIndicatorView!

var locationspickerData: [String] = [String]()

override func viewDidLoad() {
super.viewDidLoad()

populateLocations()

}


func populateLocations() {

self.locationspickerData = ["All Locations"]
let url:URL = URL(string: "http://<web address>")!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
//request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}

let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data!, options: [])
}
catch
{
return
}
guard let data_list = json as? NSArray else
{
return
}
if let locations_list = json as? NSArray
{

for i in 0 ..< data_list.count
{
if let locations_obj = locations_list[i] as? NSDictionary
{
if let location_name = locations_obj["name"] as? String
{
self.locationspickerData.append(location_name)
}
}
}


self.locationPickerOutlet.delegate = self
self.locationPickerOutlet.dataSource = self
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
self.theProgressOutlet.stopAnimating()
}

}

})

task.resume()

}



override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}


func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return locationspickerData.count
}


func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return locationspickerData[row]
}

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let titleData = locationspickerData[row]
let myTitle = NSAttributedString(string: titleData, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 15.0)!,NSForegroundColorAttributeName:UIColor.blue])
return myTitle
}

最佳答案

在DispatchQueue后面添加代码self.theProgressOutlet.stopAnimating()。试试这个

DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
//Your code
}
self.theProgressOutlet.stopAnimating()

尝试一下,看看是否有效。

关于ios - 异步 Web 请求后无法让事件指示器停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43399194/

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