2017-04-06 1 views
0
class MyOrdersViewController:UITableViewController,GMSMapViewDelegate{ 


private var username = KeychainWrapper.standard.string(forKey: "username") 


var googleStaticImages = [UIImage]() 



var OrdersByCutomer = [Booking]() 

var orderByCustomer: Booking! = Booking() 

var driverPhotoUrlString: String! 



var driverPhotoURL = [String]() 


var refreshCtrl: UIRefreshControl! 

이보기 컨트롤러는 UItabViewController에 포함 된 여러보기 컨트롤러 중 하나입니다. 이 viewController의 탭을 처음 선택하면 모든 것이 잘 작동하고 데이터 소스는 getOrdersByCustomer()에서 업데이트되며 모든 주문 셀이 표시됩니다. 그러나 다른보기 컨트롤러 (다른 탭)에서 주문을 가져 와서 self.tabBarController? .selectedIndex = 2를 사용하여이보기 컨트롤러로 다시 이동하면 다른보기 컨트롤러에서 배치 된 새 주문에 대한 JSON이 표시됩니다. 이 새로운 주문을위한 셀이 나타나지 않습니다.UItableView가 데이터를 다시로드하지 않음

viewWillAppear에서 다음 메서드를 호출하면 데이터 소스가 업데이트되고 있지만 self.tableView.reloadData()가 작동하지 않는 것 같고 새로 배치 된 순서의 셀이 표시되지 않습니다. 다른 뷰 컨트롤러

func transactionCompleted(withResponse response : NSDictionary,errorDescription error:NSError) -> Void { 
    self.dismiss(animated: true){ 

     if response.count != 0{ 

      print(response) 
     } 

     self.view.isUserInteractionEnabled = false 

    DispatchQueue.main.async { 

     self.submitBookingRequest(){(_status,_success) in 



      if _status == "yes"{ 

       self.effectView.removeFromSuperview() 

       self.view.isUserInteractionEnabled = true 

       let alertController = UIAlertController(title: "Delivery", message: "Delivery order was placed successfull!", preferredStyle: UIAlertControllerStyle.alert) 

       let closeAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel) { (alertAction) -> Void in 


        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 

        let bookNowViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewController2") as! BookNowViewController 



        self.tabBarController?.selectedIndex = 2 


        self.navigationController?.setViewControllers([bookNowViewController], animated: false) 



       } 

       alertController.addAction(closeAction) 

       self.present(alertController, animated: true, completion: nil) 





      }else{ 

       self.effectView.removeFromSuperview() 

       self.showAlertWithMessage(message: "Problem placing the order!Please Contact Customer Care", ControllerTitle: "Order", ActionTitle: "Close") 

      } 




     } 

     } 


    } 
} 

}에서

func getOrdersByCustomer(){ 

    if self.refreshCtrl.isRefreshing{ 

     self.refreshCtrl.attributedTitle = NSAttributedString(string: "Refresh orders..") 

    } 

    ARSLineProgress.ars_showOnView(self.view) 


    Alamofire.request("http://www.*******************************************************ordersbyUser.php?", method: .get, parameters: ["username":username!], encoding: URLEncoding.default).responseString { response in 
     print(response.request ?? "") // original URL request 
     print(response.response ?? "") // URL response 
     print(response.data!)  // server data 
     print(response.result) // result of response serialization 

     if let JSON = response.result.value { 
      print("Get Orders By User JSON: " , JSON) 


      var jsonObject: [AnyObject]! 


      do{ 
       jsonObject = try JSONSerialization.jsonObject(with: response.data!, options:JSONSerialization.ReadingOptions.allowFragments) as? Array 



       print(jsonObject) 

       if jsonObject.isEmpty{ 

        ARSLineProgress.hideWithCompletionBlock { 

         self.showAlertWithMessage(message: "No orders found.Use the Book Now tab to order!", ControllerTitle: "My Orders", ActionTitle: "OK") 

         if self.refreshCtrl.isRefreshing{ 
          self.refreshCtrl.endRefreshing() 
         } 


        } 

       } 


      } catch let error as NSError { 
       print(error) 

      } 

      var jsonElement: [String:AnyObject] 


      for i in 0 ..< jsonObject.count 
      { 


       jsonElement = jsonObject[i] as! Dictionary 





       let staticUrl = jsonElement["staticurl"] as? String 

       let orderID = jsonElement["orderid"] as? String 
       let customerPrice = jsonElement["userprice"] as? String 
       let orderTime = jsonElement["order_time"] as? String 
       let orderStatus = jsonElement["stat"] as? String 

       let pickUpLatitude = jsonElement["plat"] as? String 

       let pickUpLongitude = jsonElement["plon"] as? String 
       let dropOffLatitude = jsonElement["dlat"] as? String 

       let dropOffLongitude = jsonElement["dlon"] as? String 

       let driverphotoURL = jsonElement["driver_photo"] as? String 

       print(jsonElement) 



       let booking = Booking() 

       booking.orderId = orderID! 
       booking.price = "₹" + customerPrice! 
       booking.pickUpTime = orderTime! 
       booking.status = orderStatus! 
       booking.pickUpLatitude = pickUpLatitude! 
       booking.pickUpLongitude = pickUpLongitude! 
       booking.dropOffLatitude = dropOffLatitude! 
       booking.dropOffLongitude = dropOffLongitude! 
       booking.staticUrl = staticUrl! 

       DispatchQueue.main.async{ 


        self.OrdersByCutomer.append(booking) 

        if driverphotoURL != nil { 

        self.driverPhotoURL.append(driverphotoURL!) 

         self.refreshTable() 

        } 


       } 

      } 

      if self.refreshCtrl.isRefreshing{ 
       self.refreshCtrl.endRefreshing() 
       self.refreshCtrl.attributedTitle = NSAttributedString(string: "Pull to refresh orders") 
      } 

      ARSLineProgress.hide() 


     } 
    } 

     } 


func refreshTable(){ 

    DispatchQueue.main.async { 

     self.tableView.reloadData() 

    } 


} 

override func numberOfSections(in tableView: UITableView) -> Int { 

return 1 
} 


override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    return OrdersByCutomer.count 


} 


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

    print("CELL FOR ROW AT INDEX EXCECUTED") 

    self.orderByCustomer = self.OrdersByCutomer[(indexPath as NSIndexPath).row] 

    self.driverPhotoUrlString = self.driverPhotoURL[(indexPath as NSIndexPath).row] 

    let cell = tableView.dequeueReusableCell(withIdentifier: "MyOrdersCell", for: indexPath) as! MyOrdersCell 


    cell.contentView.layer.borderColor = UIColor.clear.cgColor 

    cell.contentView.layer.borderWidth = 10 


    let staticMapsURL = URL(string:orderByCustomer.staticUrl) 

    let p = Bundle.main.path(forResource: "39", ofType: "gif")! 
    let data = try! Data(contentsOf: URL(fileURLWithPath: p)) 

    cell.googleStaticMapImageView.kf.indicatorType = .image(imageData: data) 

    cell.googleStaticMapImageView.kf.setImage(with: staticMapsURL) 

    // if driver photo is not available use default image 

    if driverPhotoUrlString.contains("600x300"){ 

     cell.driverProfileImage.image = UIImage.init(named: "DriverImage.png") 

     cell.driverProfileImage.backgroundColor = UIColor.lightGray 

    }else{ 


    let driverPhotoURL = URL(string: driverPhotoUrlString) 

     cell.driverProfileImage.kf.setImage(with: driverPhotoURL) 

    cell.driverProfileImage.kf.indicatorType = .activity 

    } 

    // make the driver profile picture cicular 

    cell.driverProfileImage.layer.borderWidth = 1 
    cell.driverProfileImage.layer.masksToBounds = false 
    cell.driverProfileImage.layer.borderColor = UIColor.black.cgColor 
    cell.driverProfileImage.layer.cornerRadius = cell.driverProfileImage.frame.height/2 
    cell.driverProfileImage.clipsToBounds = true 



    cell.orderIdLabel.text = orderByCustomer.orderId 

    cell.orderTimeLabel.text = orderByCustomer.pickUpTime 


    cell.userPriceLabel.text = orderByCustomer.price 

    cell.statusLabel.text = orderByCustomer.status 



    return cell 



} 



override func viewWillAppear(_ animated: Bool) { 

    super.viewWillAppear(true) 

    self.animateTable() 

    DispatchQueue.main.async { 


    self.getOrdersByCustomer() 

    } 

    print("ViewWillAppear") 




} 

override func viewDidLoad() { 

    super.viewDidLoad() 

    tableView.delegate = self 
    tableView.dataSource = self 



    print("ViewDidLoad") 


    self.refreshCtrl = UIRefreshControl() 
    self.refreshCtrl.addTarget(self, action: #selector(self.getOrdersByCustomer), for: .valueChanged) 
    self.refreshCtrl.attributedTitle = NSAttributedString(string: "Pull to refresh orders") 
    self.refreshControl = self.refreshCtrl 


} 

방법

+0

대리인 및 데이터 원본의 구현은 어디에 있습니까? –

+0

self.tableView가 올바른 테이블 뷰인지 확인할 수 있습니까? 만약 당신이 저장하기 전에 'tableView (_ tableView : UITableView, numberOfRowsInSection 섹션 : Int) -> Int'에 중단 점을 추가하고 함수가 호출되는지 확인하기 위해 앱을 여는 -> 주문 추가 -> 시도 할 수 있습니다. 그것이 호출되면 그것은'getOrdersByCustomer()'와 관련된 문제이며, 그렇지 않으면 올바른 tableview를 새로 고치지 못할 수도 있습니다. 테이블 뷰는 처음 렌더링 될 때 자동으로 새로 고침되기 때문에 처음으로 작동합니다. –

+0

@Alex S viewDidLoad()에 있습니다. 질문을 업데이트했습니다. –

답변

0

문제는 getOrdersByCustomer()과 관련이 있습니다. 뷰가 나타날 때마다 해당 메서드를 호출하고 새 레코드를 OrdersByCutomer 배열에 추가합니다. 그러나 매번 배열을 비우지 않으므로 첫 번째로 "10 개"레코드가 표시되고 다음에 새로 추가 된 레코드가 끝나는 다음에 "21"레코드가 표시됩니다.

0
viewDidLoad() 

당신이 UITabBarController가에 탭을 변경할 때 다시 실행되지 않습니다. 그 작동 방식을 확인하려면 탭에 표시된 VC의 각 viewDidLoads에 인쇄물 ("")을 집어 넣으십시오. 앱을 실행하면 표시되는 시점을 기준으로하지 않고 처음에 모든 인쇄본을 볼 수 있습니다 화면에.

NSNotificationCentre 또는 어떤 종류의 리스너를 사용하면 이러한 일이 발생할 수 있습니다. 이 작업을 수행하기에 좋은 라이브러리이거나 사과 문서를 따를 수 있습니다.

https://github.com/100mango/SwiftNotificationCenter

당신이 생각해야 할 일의 일반적인 요점은 '순서로 배치'기능에 이벤트 이미 터 및 명령을 표시하여 VC에 리스너를 설정합니다.

+0

'viewDidLoad'가 아닌'viewWillAppear'에서 업데이트가 일어나고 있습니다 –

관련 문제