2016-12-24 77 views
-1

我想將Google API當前位置函數中出現的每個place.name添加到我的數組suggestedLocations。當我打印下面的數組時,它總是空着。Swift .append到數組不工作

我的目標是有一個數組,列出當地的地方。我錯過了什麼?

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

在***異步***數據請求完成之前,您可能正在打印數組的內容。 – luk2302

+0

顯示您的打印位置。 – shallowThought

+0

@ luk2302感謝您的建議。我能做些什麼來解決這個問題? 'print'顯示調試日誌中的列表,但當我嘗試在最後括號下面打印數組但仍然在ViewDidLoad中時,數組顯示爲空白。 – flakedev

回答

0

根據您的意見,您的printarray低於最終括號但仍然viewDidLoad內。這就是爲什麼它是空的原因,placesClient.currentPlace還沒有完成運行,因爲它是一個塊方法。

您應該調用打印函數來顯示最新的完成數組。嘗試使用此更新代碼:

//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()