2016-12-24 1 views
-1

Google API 현재 위치 함수에서 나온 모든 place.name을 내 배열 suggestedLocations에 추가하려고합니다. 아래의 배열을 인쇄하면 항상 비어 있습니다.Swift. 배열에 제대로 작동하지 않습니다.

내 목표는 지역 장소를 나열하는 배열을 갖는 것입니다. 내가 뭘 놓치고 있니?

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

는 귀하의 의견, array에 대한 print에 따르면 마지막 괄호 아래 여전히 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()으로 전화 할 수도 있습니다.

관련 문제