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
}
방법
대리인 및 데이터 원본의 구현은 어디에 있습니까? –
self.tableView가 올바른 테이블 뷰인지 확인할 수 있습니까? 만약 당신이 저장하기 전에 'tableView (_ tableView : UITableView, numberOfRowsInSection 섹션 : Int) -> Int'에 중단 점을 추가하고 함수가 호출되는지 확인하기 위해 앱을 여는 -> 주문 추가 -> 시도 할 수 있습니다. 그것이 호출되면 그것은'getOrdersByCustomer()'와 관련된 문제이며, 그렇지 않으면 올바른 tableview를 새로 고치지 못할 수도 있습니다. 테이블 뷰는 처음 렌더링 될 때 자동으로 새로 고침되기 때문에 처음으로 작동합니다. –
@Alex S viewDidLoad()에 있습니다. 질문을 업데이트했습니다. –