У моего приложения есть экран, который использует контроллер табличного представления для отображения списка ресторанов с изображениями, я использую Alamofire и AlamofireImage.Когда я запускаю приложение в первый раз, я захожу на экран входа в систему или регистрации, он работает просто отлично, но когда я вхожу в систему, он переходит на экран списка ресторанов и зависает, не реагируя на прикосновения.Но когда я закрываю приложение и запускаю его снова, оно работает просто отлично.
вот мой код для контроллера ресторана
import UIKit
import Alamofire
import AlamofireImage
import SwiftyJSON
import Toast_Swift
class RestaurantsVC: UITableViewController {
let URL_REQUEST_RESTAURANTS = "http://wajabatonline.ly/api/restaurants"
let userDefs = UserDefaults.standard
var restaurantId:integer_t = -1
var restaurants = [RestaurantModel]()
@IBAction func btnDrawer(_ sender: UIBarButtonItem) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.drawerController.setDrawerState(.opened, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// init cart button.
let rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "basket"), style: .done, target: self, action: #selector(btnCart))
self.navigationItem.rightBarButtonItem = rightBarButtonItem
}
override func viewDidAppear(_ animated: Bool) {
// request restaurants
requestRestaurants(token: userDefs.string(forKey: Constatnts.defaultsKeys.userToken)!, city: "Benghazi")
}
@objc func btnCart(){
let mStoryboard = UIStoryboard(name: "Main", bundle: nil)
let controller = mStoryboard.instantiateViewController(withIdentifier: "CartVC")
self.present(controller, animated: true, completion: nil)
}
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 restaurants.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "restaurantCell", for: indexPath) as! RestaurantViewCell
cell.selectionStyle = .none
let restaurant = restaurants[indexPath.row]
// if restaurant closed then show closed sign
if restaurant.open == 0 {
cell.imgDark.isHidden = false
cell.lblClosed.isHidden = false
} else {
cell.imgDark.isHidden = true
cell.lblClosed.isHidden = true
}
// Init and download image
let url = URL(string: restaurant.img_url)!
let placeholderImage = UIImage(named: "ph2")!
let filter = AspectScaledToFillSizeFilter(
size: cell.restaurantImgView.frame.size
)
cell.restaurantImgView.af_setImage(withURL: url, placeholderImage: placeholderImage, filter: filter, imageTransition: .crossDissolve(0.1))
cell.restaurantNameLbl?.text = restaurant.name
cell.restaurantCuisineLbl?.text = restaurant.descriptions
return cell
}
// Get selected row
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// if closed return
if restaurants[indexPath.row].open == 0 {
DispatchQueue.main.async{
HelperFuncs.helper.showAlert("المطعم مغلق حاليا!", vc: self)
}
return
}
restaurantId = restaurants[indexPath.row].id
performSegue(withIdentifier: "RestaurantVCSegue", sender: self)
}
// Send data with segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination is RestaurantInfoVC{
let vc = segue.destination as? RestaurantInfoVC
vc?.restaurantId = self.restaurantId
}
}
func goToScreen() {
let wajabatStoryBoard = self.storyboard
guard let dVC = wajabatStoryBoard?.instantiateViewController(withIdentifier: "RestaurantInfoVC") as? RestaurantInfoVC
else {
print("No ctrl found")
return
}
self.navigationController?.pushViewController(dVC, animated: true)
}
func requestRestaurants(token:String, city:String) {
HelperFuncs.helper.showActivityIndicator(vc: self)
// 1- creating parameters for the post request
let parameters: Parameters=[
"src": "mobile",
"token": token,
"city": city
]
// 2- Sending http post request
Alamofire.request(URL_REQUEST_RESTAURANTS, method: .post, parameters: parameters).responseJSON { response in
switch response.result {
case .success(let value):
let jsonResponse = JSON(value)
// Check if status = success
if jsonResponse["status"] == "success" {
// Map array of restaurants to restaurants objects
let restaurantsList = jsonResponse["restaurants"].arrayValue
// reset restaurants array to 0, if come from view did appear do not duplicate
self.restaurants.removeAll()
// Loop through each restaurant element in the array of json
for restaurant in restaurantsList {
self.restaurants.append(RestaurantModel(id: restaurant["id"].int32Value, img_url: restaurant["img_url"].stringValue, name: restaurant["name"].stringValue, descriptions: restaurant["description"].stringValue, delivery_fee: restaurant["delivery_fee"].floatValue, city: restaurant["city"].stringValue, note: restaurant["delivery_fee"].stringValue, lat: restaurant["delivery_fee"].doubleValue, lng: restaurant["delivery_fee"].doubleValue, leastPrice: restaurant["note"].floatValue, commission: restaurant["commission"].floatValue, open: restaurant["open"].int32Value, enabled: restaurant["enabled"].int32Value))
}
self.tableRefresh()
HelperFuncs.helper.hideActivityIndicator(vc: self)
} else {
HelperFuncs.helper.hideActivityIndicator(vc: self)
HelperFuncs.helper.showToast(jsonResponse["message"].stringValue, self)
if jsonResponse["message"].stringValue.starts(with: "i") {
HelperFuncs.helper.setLoggedoutDefs()
}
}
case .failure( _):
HelperFuncs.helper.hideActivityIndicator(vc: self)
HelperFuncs.helper.showToast("خطأ في الشبكة!", self)
self.networkAlert()
}
}
}
func tableRefresh(){
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
// alert with action
func networkAlert() {
let alert = UIAlertController(title: "لا يوجد اتصال", message: nil, preferredStyle: .alert)
// Main Actions
alert.addAction(UIAlertAction(title: "اعادة التحميل", style: .default, handler: { (action) -> Void in
self.requestRestaurants(token: self.userDefs.string(forKey: Constatnts.defaultsKeys.userToken)!, city: "Benghazi")
}))
// show alert
self.present(alert, animated: true)
}
@IBAction func unwindToRestaurants(_ sender: UIStoryboardSegue){
}
}
И я показываю экран ресторана с библиотекой выдвижных ящиков изпредыдущий контроллер по этому коду:
// Init Drawer
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let storyBoard = UIStoryboard.init(name: "Main", bundle: Bundle.main)
let navVC = storyBoard.instantiateViewController(withIdentifier: "NavVC") // is the main controller for the drawer.
let drawerVC = storyBoard.instantiateViewController(withIdentifier: "DrawerVC") // is the drawer, and the drawer needs a main controller
appDelegate.drawerController.mainViewController = navVC
appDelegate.drawerController.drawerViewController = drawerVC
appDelegate.window?.rootViewController = appDelegate.drawerController
appDelegate.window?.makeKeyAndVisible()
Это проблема основного потока?