2017-02-23 2 views
0

내 큰 프로젝트의 일부인 내 VC 중 하나에 다음 코드가 있습니다. Firebase DB 참조 중 하나는 Sell_Request입니다. 3 명의 자녀 (name, latitudelongitude)가 있지만 지금은 name과 관련이 있습니다.TableView 셀에 Firebase의 데이터 표시

문자열 배열에 추가하려고하고 콘솔에도 인쇄하려고합니다. 콘솔에 인쇄되는 이름이 보이지만 개별 셀에 인쇄 된 이름이 표시되지 않습니다.

감사합니다. 데이터 소스 후 다시로드

import UIKit 
import Firebase 
import FirebaseDatabase 
import MapKit 
import CoreLocation 

class RequestVC: UITableViewController, CLLocationManagerDelegate { 

    var locationManager = CLLocationManager() 
    var sellerUserNames = [String]() 

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     if segue.identifier == "backToMain" { 
      self.navigationController?.navigationBar.isHidden = true 
     } 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.requestWhenInUseAuthorization() 
     locationManager.startUpdatingLocation() 

    } 

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
     if let location = manager.location?.coordinate { 
      let databaseRef = FIRDatabase.database().reference() 
      databaseRef.child("Sell_Request").queryOrderedByKey().observe(.childAdded, with: { (FIRDataSnapshot) in 

       if let data = FIRDataSnapshot.value as? NSDictionary { 
        if let name = data[Constants.NAME] as? String { 
           self.sellerUserNames.append(name) 
           print(name) 
           } 
          } 
         }) 
        } 
       } 


    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 



    // MARK: - Table view data source 

    override func numberOfSections(in tableView: UITableView) -> Int { 
     // #warning Incomplete implementation, return the number of sections 
     return 1 
    } 

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     // #warning Incomplete implementation, return the number of rows 
     return sellerUserNames.count 
    } 


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 

     cell.textLabel?.text = sellerUserNames[indexPath.row] 

     return cell 
    } 


    /* 
    // Override to support conditional editing of the table view. 
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { 
     // Return false if you do not want the specified item to be editable. 
     return true 
    } 
    */ 

    /* 
    // Override to support editing the table view. 
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
     if editingStyle == .delete { 
      // Delete the row from the data source 
      tableView.deleteRows(at: [indexPath], with: .fade) 
     } else if editingStyle == .insert { 
      // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
     }  
    } 
    */ 

    /* 
    // Override to support rearranging the table view. 
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { 

    } 
    */ 

    /* 
    // Override to support conditional rearranging of the table view. 
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { 
     // Return false if you do not want the item to be re-orderable. 
     return true 
    } 
    */ 

    /* 
    // MARK: - Navigation 

    // In a storyboard-based application, you will often want to do a little preparation before navigation 
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     // Get the new view controller using segue.destinationViewController. 
     // Pass the selected object to the new view controller. 
    } 
    */ 

} 
+1

수를 확인할 수 있습니까? 0A가 아닙니다. 메인 라인의 인쇄 라인 재로드 테이블 이후. –

+1

안녕하세요, 당신은 tableview를 다시로드해야합니다. 귀하의 tableview 이름의 참조를 추가하십시오. tableView, if let 데이터 문의 끝에 self.tableView.reloadData()를 추가하십시오. – webjunkie

+0

응답 해 주셔서 감사합니다. 변수 (var tableView : UITableView!)를 만들거나 IBOutlet (@IBOutlet var tableView : UITableView!) 또는 다른 것을 만드는 것을 의미합니까? – user2411290

답변

1

당신은 그냥 ...

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    if let location = manager.location?.coordinate { 
     let databaseRef = FIRDatabase.database().reference() 

     sellerUserNames.removeAll() 
     databaseRef.child("Sell_Request").queryOrderedByKey().observe(.childAdded, with: { (FIRDataSnapshot) in 

      if let data = FIRDataSnapshot.value as? NSDictionary { 
       if let name = data[Constants.NAME] as? String { 
          self.sellerUserNames.append(name) 
          print(name) 
          self.tableView.reloadData() 
          } 
         } 
        }) 
       } 
      } 

편집

/당신이 sellerUserNames 배열에 이름을 추가 한 후, tableView.reloadData()을 부르는 당신의 기능을 변경해야 sellerUserNames.removeAll()에 전화를 걸려면 코드 및 테이블보기의 수명주기에 따라 다르지만 위 코드를 편집하여 코드가 가장 많은 부분에 추가하십시오 적절하게.

+0

감사! 그것은 그것을하는 것처럼 보였다. .. 나는 또 다른 문제를 가지고있는 것처럼 보인다. 나는 같은 이름이 반복되고있다. 관련된 몇 가지 질문을 살펴 봤는데, 함수의 어딘가에서 self.sellerUserNames.removeAll()을 호출하면 문제의 빠른 수정이 이루어져야한다. 그러나 문제의 이름 만 표시한다. – user2411290

+0

나는 그 문제를 해결해야하는'sellerUserNames.removeAll()'에 대한 호출을 포함하도록 나의 대답을 편집했다. – MikeG

0

TableView 필요가 변경 코드에서 sellerUserNames을 즉있다. 따라서 sellerUserNames에 이름을 추가 한 후에는 tableview를 다시로드해야합니다.

이름을 추가 한 후이 코드 줄을 추가하십시오.

self.tableView.reloadData()

관련 문제