Firebase中的数组不会附加

时间:2018-04-09 12:47:27

标签: ios swift firebase

我最近有了我的代码,但是我更改了代码,现在我不明白为什么,但是现在我从firebase获取的数组正在打印,但是没有附加到UITableView。它以前工作过,但我不知道出了什么问题。此外,当它工作时,它也是重复的。这是我目前的代码:

    @IBOutlet weak var nearbyTableView: UITableView!
var myList: [String] = []
var handle:DatabaseHandle?
var ref:DatabaseReference?
var locationManager:CLLocationManager!


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return myList.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
    var (cellName) = myList[indexPath.row]
    cell.textLabel?.text = cellName
    return cell

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
    var (cellName) = myList[indexPath.row]



    let viewController = self.storyboard?.instantiateViewController(withIdentifier: "Home2") as! ShopViewController
    viewController.name = cellName
    self.present(viewController, animated: true, completion: nil)
    navigationController?.pushViewController(viewController, animated: true)

    print("row\(indexPath.row)")
    print("name: \(cellName)")
}


override func viewDidLoad() {
    super.viewDidLoad()
            determineMyCurrentLocation()
}

func determineMyCurrentLocation() {
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.startUpdatingLocation()
    }

}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let messageDB = Database.database().reference().child("shops")

    messageDB.observe(.childAdded, with: { snapshot in

        let snapshotValue = snapshot.value as! NSDictionary
        let text = snapshotValue["name"] as! String

        let userLocation:CLLocation = locations[0] as CLLocation



        self.myList.append(text)
    })

    self.nearbyTableView.reloadData()
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
    print("Error \(error)")
}

非常感谢

1 个答案:

答案 0 :(得分:1)

尝试按以下方式更改didUpdateLocations,而非100%确定,但它可以帮助您

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let messageDB = Database.database().reference().child("shops")

    messageDB.observeSingleEvent(of: .childAdded, with: { snapshot in

        let snapshotValue = snapshot.value as! NSDictionary
        let text = snapshotValue["name"] as! String

        let userLocation:CLLocation = locations[0] as CLLocation

        self.myList.append(text)
        self.nearbyTableView.reloadData()

    })

}