我在做什麼錯誤?我知道代碼工作,因爲我從另一個視圖控制器返回時獲取單元格中的位置,但它在第一次加載應用程序時不會出現。我一直盯着這個眼睛!加載應用程序時無法獲取位置,但從另一個視圖控制器傳遞時
任何幫助表示讚賞。
下面的代碼:
import UIKit
import CoreLocation
class ViewController: UITableViewController {
var arrayLocations:[[Double]] = [[27.1750199, 78.0399665]]
var annotationAddress = ""
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
if !arrayLocations.isEmpty {
arrayLocations = UserDefaults.standard.array(forKey: "arrayLocations") as? [[Double]] ?? [[Double]]()
print("Table view is loaded")
}
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayLocations.count
}
override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
getLocationAddress(location: CLLocation(latitude: arrayLocations[indexPath.row][0], longitude: arrayLocations[indexPath.row][1]))
cell.textLabel?.text = annotationAddress
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// activeRow = indexPath.row
performSegue(withIdentifier: "toMapViewController", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toMapViewController" {
let mapViewController = segue.destination as! MapViewController
mapViewController.arrayLocations = arrayLocations
}
}
func getLocationAddress(location: CLLocation) {
CLGeocoder().reverseGeocodeLocation(location) { (placemarks, error) in
if error != nil {
print(error!)
} else {
if let placemark = placemarks?[0] {
var address = ""
if placemark.subThoroughfare != nil {
address += placemark.subThoroughfare! + " "
}
if placemark.thoroughfare != nil {
address += placemark.thoroughfare!
}
self.annotationAddress = address
if self.annotationAddress.isEmpty {
self.annotationAddress = "Lat: \(location.coordinate.latitude) and Lon: \(location.coordinate.longitude)"
}
}
}
}
}
太棒了,謝謝!工作過一種享受!現在我只需要弄清楚它爲什麼能起作用;;) – Aecasorg
它是因爲reverseGeocodeLocation異步調用而工作的。 – KKRocks
標記爲接受,如果您的問題與我的答案解決, – KKRocks