Webインジケータが作成されるたびにアクティビティインジケータが開始され、完了したら停止する必要があります。今すぐインジケータが表示されますが、.stopAnimation
はすぐに実行されており、Webリクエストが完了するのを待っていません。は、非同期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
}
たぶん、あなたのWeb要求が;-)速いということです。 Btw:インジケータがエラーの場合に停止しないと考えてください。これは 'defer'ステートメントの良い例です。 – vadian
PS:...そして通常のアドバイス:ネイティブのSwiftの対応があり、SwiftのNSArray、NSDictionaryのいずれでもない場合は、NSMutable ...を使用しないでください。 – vadian
NSDictionaryの代替手段はありますか? – t2nator