目前在cellForRowAtIndexPath
内同步使用Alamofire查询来自Heroku的JSON数组,并在for循环中,使用图像和文本属性从JSON数组中的每个JSON对象创建一个结构,然后将每个结构附加到表视图控制器中的数组属性。这并不奇怪,这真的很慢。在应用程序启动时,初始VC是一个容器VC,根据用户是否“登录”显示导航控制器或页面VC。页面VC中的初始VC是容纳VC的容器VC。
我对GCD和并发概念完全陌生。想知道如何填充我的数组作为每个表视图单元格的基础数据。
这是我当前的代码 - 更改了一些变量名称,因为我为这个项目签了一份NDA:
import UIKit
import Alamofire
import Alamofire_Synchronous
final class PopularPearsTableViewController: UITableViewController {
let screenSize: CGRect = UIScreen.main.bounds
var pears: [Pear] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(PopularPearTableViewCell.self, forCellReuseIdentifier: "popularPear")
tableView.rowHeight = (screenSize.height) * 0.3
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - Table View Data Source
extension PopularShopsTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// just a stub, will be replaced with dynamic code later on
return 5
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print(#function)
let cell = tableView.dequeueReusableCell(withIdentifier: "popularPear", for: indexPath) as! PopularPearTableViewCell
let userDefaults = UserDefaults.standard
guard let pearUUID = userDefaults.string(forKey: "pearUUID"),
let pearToken = userDefaults.string(forKey: "pearToken")
else {
return cell
}
if indexPath.row == 0 {
let header = createAuthenticatedHeader(user: pearUUID, password: pearToken)
let pearResponse = Alamofire.request("url", headers: header).responseJSON()
if let pearsFromResponse = (pearResponse.result.value! as! JSON)["data"] as? [JSON] {
for pear in pearsFromResponse {
let name = pear["name"] as! String
let pictureURL = pear["picture_url"] as! String
let imageURL = URL(string: pictureURL)
let imageData = NSData(contentsOf: imageURL!)
let image = UIImage(data: imageData as! Data)!
let newPear = Pear(name: name, image: image)
self.pears.append(newPear)
}
}
}
cell.giveCell(pearImage: pears[indexPath.row].image, pearName: pears[indexPath.row].name)
return cell
}
}