Swift .append到数组不工作

时间:2016-12-24 23:36:08

标签: arrays swift google-maps google-api

我想将Google API当前场所功能中的每个place.name添加到我的阵列suggestedLocations。当我打印下面的数组时,它总是空出来的。

我的目标是有一个列出本地地方的数组。我错过了什么?

class AddPersonVC: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var firstLocationNameBtn: UIButton!
@IBOutlet weak var secondLocationNameBtn: UIButton!

var manager = CLLocationManager()

var updateCount = 0
var zoomLevel = 200
var suggestedLocations = [String]()

override func viewDidLoad() {
    super.viewDidLoad()


    manager.delegate = self

    // Users current location
    if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
        mapView.showsUserLocation = true

        manager.startUpdatingLocation()
    } else {
        manager.requestWhenInUseAuthorization()
    }

    // Find all local places
    let placesClient = GMSPlacesClient()
    placesClient.currentPlace(callback: { (placeLikelihoodList, error) -> Void in
        if let error = error {
            print("Pick Place error: \(error.localizedDescription)")
            return
        }

        if let placeLikelihoodList = placeLikelihoodList {
            for likelihood in placeLikelihoodList.likelihoods {
                let place = likelihood.place
                suggestedLocations.append(place.name)
                print("Current Place name \(place.name) at likelihood \(likelihood.likelihood)")
                //print("Current Place address \(place.formattedAddress)")
                //print("Current Place attributions \(place.attributions)")
                //print("Current PlaceID \(place.placeID)")
            }
        }
    })

1 个答案:

答案 0 :(得分:0)

根据您的评论,print array位于最后一个括号内,但仍位于viewDidLoad内。这就是它为空的原因,placesClient.currentPlace还没有完成运行,因为它是一个块方法。

您应该调用print函数来显示最新的完成数组。尝试使用以下代码更新代码:

//remain the above code as it is
    if let placeLikelihoodList = placeLikelihoodList {
        for likelihood in placeLikelihoodList.likelihoods {
            let place = likelihood.place
            suggestedLocations.append(place.name)
            print("Current Place name \(place.name) at likelihood \(likelihood.likelihood)")
            //print("Current Place address \(place.formattedAddress)")
            //print("Current Place attributions \(place.attributions)")
            //print("Current PlaceID \(place.placeID)")
        }
    self.printArray()  //Add a function call on what you want to do with the array here.
    }
})

func printArray() {
    print(suggestedLocations)
}

这只是向您展示如何获取打印数组的示例。如果您要重新加载tableView,也许您也可以在此处致电self.tableView.reloadData()