首页 > 解决方案 > For Loop 未在 ViewDidLoad 中运行 - 其他一切都是

问题描述

下载餐厅函数返回 2,所以这不是空数组的问题。但是,当我尝试获取数组中的每个值并将其放入我的 for 循环以向地图添加注释时,什么也没有发生。没有打印声明,没有注释。我的当前循环中有一条打印语句,但它没有运行,但我不确定它为什么没有运行。

我尝试将 for 循环放在它自己的函数中,并将其放在下载函数之后,但没有区别。

我包含了整个代码,以最好地提供有关此问题的所有信息

import UIKit
import CloudKit
import SafariServices
import MapKit
import GoogleMobileAds

class InterFood: UIViewController, MKMapViewDelegate {
    @IBOutlet weak var myMap: MKMapView!

    var bannerView: GADBannerView!
    var restaurantArray: Array<CKRecord> = []
    var index: NSIndexPath!
    var pin: AnnotationPin!

    override func viewDidLoad() {
        super.viewDidLoad()

        print("Hi")

        self.myMap.delegate = self

        self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil)

        func downloadRestaurants () {
            let publicDB = CKContainer.default().publicCloudDatabase
            let predicate = NSPredicate(value: true)
            let query = CKQuery(recordType: "InternationalCenter", predicate: predicate)

            query.sortDescriptors = [NSSortDescriptor(key: "Name", ascending: true)]

            publicDB.perform(query, inZoneWith: nil) { (results, error) -> Void in
                if (error != nil) {
                    print("Error" + (error?.localizedDescription)!)
                } else {
                    for result in results! {
                        self.restaurantArray.append(result)
                    }
                    OperationQueue.main.addOperation( { () -> Void in
                        self.myMap.reloadInputViews()
                        //   activityIndicator.isHidden = true
                        print("Downloading")
                        print(self.restaurantArray.count)
                    })
                }
            }
        }

        downloadRestaurants()

        print("Hi Again")

        self.title = "International Center"

        let coordinate = CLLocationCoordinate2D(latitude: 42.722869, longitude: -84.488012)

        let region = MKCoordinateRegionMakeWithDistance(coordinate, 2000, 2000)

        myMap.setRegion(region, animated: true)

        for res in restaurantArray {
            pin = AnnotationPin(title: res.value(forKey: "Name") as! String, subtitle: "Address", theCoordinates: res.value(forKey: "Location") as! CLLocationCoordinate2D, theWeb: "https://google.com")

            myMap.addAnnotation(pin)

            self.myMap.reloadInputViews()
        }
    }
}

我试过实现这里描述的这个函数,但没有成功,因为我们的代码非常相似:how to setup array for multi annotations with swift

在此处输入图像描述

标签: swiftfor-loopmapkitmkannotationckrecord

解决方案


迭代时 restaurantArray 为空的原因是查询是异步执行的。viewDidLoad()将在您的查询返回结果之前完整执行。您可以在程序的输出中看到这一点。即使您downloadRestaurants()先打电话,它也会在“下载”之前打印“Hi Again”。


推荐阅读