2017-05-31 29 views
0

我想創建一個地址數組,基於我將在下面附加的反向地址代碼函數。然而,每當我從一系列價值觀中輸入緯度和經度,然後將它追加到我的地址時代時,時代的秩序總是會變得混亂。這裏是我的代碼:數組值的不同排列

func getAddressFromLatLon(pdblLatitude: Double, withLongitude pdblLongitude: Double){ 
    var center : CLLocationCoordinate2D = CLLocationCoordinate2D() 
    let lat: Double = pdblLatitude 
    //21.228124 
    let lon: Double = pdblLongitude 
    //72.833770 
    let ceo: CLGeocoder = CLGeocoder() 
    center.latitude = lat 
    center.longitude = lon 

    let loc: CLLocation = CLLocation(latitude:center.latitude, longitude: center.longitude) 


    ceo.reverseGeocodeLocation(loc, completionHandler: 
     {(placemarks, error) in 
      if (error != nil) 
      { 
       print("reverse geodcode fail: \(error!.localizedDescription)") 
      } 
      let pm = placemarks! as [CLPlacemark] 

      if pm.count > 0 { 
       let pm = placemarks![0] 
       print(pm.country) 
       print(pm.locality) 
       print(pm.subLocality) 
       print(pm.thoroughfare) 
       print(pm.postalCode) 
       print(pm.subThoroughfare) 

       if pm.subThoroughfare != nil { 
        addressString = addressString + pm.subThoroughfare! + " " 
       } 
       if pm.thoroughfare != nil { 
        addressString = addressString + pm.thoroughfare! + ", " 
       } 
       if pm.locality != nil { 
        addressString = addressString + pm.locality! + ", " 
       } 
       if pm.administrativeArea != nil { 
        addressString = addressString + pm.administrativeArea! + " " 
       } 
       if pm.postalCode != nil { 
        addressString = addressString + pm.postalCode! + " " 
       } 
       print (addressString) 
       addressStrings.append(addressString) 
       addressString = "" 
      } 
    }) 
} 

func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) { 
    print(#function) 
} 


@IBAction func onSearh(_ sender: Any) { 
    for i in 0 ..< ((stores!.count)-1) { 
     print (latitudes[i]) 
     print (longitudes[i]) 
     getAddressFromLatLon(pdblLatitude: latitudes[i], withLongitude: longitudes[i]) 
    } 

我在想,如果你可以在你的項目中輸入驗證或找出原因的作用是讓我對相同的輸入不同的輸出確定性?

+0

我不明白你的問題是什麼。我測試了你的'getAddressFromLatLon'函數,它似乎工作。 –

回答

0

反向地理編碼是一種異步功能,因爲它是一個網絡請求,因此您的函數調用可能不會按照它們被調用的順序返回。

如果您需要它們的順序與它們被調用的順序完全相同,則可以在串行隊列中運行getAddressFromLatLon函數。這將確保您的結果的順序,但它會有性能上的缺陷,因爲在這種情況下,您的網絡請求無法併發運行。

如果我是你,我會將我的數據結構更改爲一個結構體,從中我可以訪問具有標識符而不是索引的元素(例如,具有標識符作爲鍵和地址作爲值的字典)。在這種情況下,您仍然可以同時運行反向地理編碼功能。