我从json API中调用数据调用表视图填充但是非常慢并且在向下滚动时滞后如何加速表的加载。我是swift的新手,xcode任何提示都会很感激
import Foundation
import UIKit
class featuredViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
// Array for JSON Data
var property: [featuredClass.property] = []
var imageArray = [String]()
var imageCollection = [[String]]()
var refreshControl: UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
self.getProperties()
// Do any additional setup after loading the view, typically from a nib.
refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: #selector(featuredViewController.getProperties), for: UIControlEvents.valueChanged)
tableView.addSubview(refreshControl)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/***********************************************************************************************/
func getProperties() {
let downloadTask = APICalls.getFeatured()
URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in
if let httpResponse = response as? HTTPURLResponse {
print("statusCode: \(httpResponse.statusCode)")
}
/******** Parse JSON **********/
do { // A Dictionary of Dictionaries
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
if let jsonDict = jsonObject as? NSDictionary {
// Do smthg.
//print(jsonDict) // Debug the json
let meCount = Int((jsonDict.count)) - 1; //get number to use for our loop
for index in 0...meCount {
for (_, value) in jsonDict { //Turns every key's value into a dictionary
// Fill property struct from json
self.property.append(featuredClass.property.init(jsonDict: value as! NSDictionary))
//print(self.property) // Uncomment for debugging
/** Get Image 0 for featured Image **/
let myData = self.property[index].image
// print(myData ?? "Error")
if myData?["0"] != nil {
let myData2 = myData?["0"] as! NSDictionary
self.imageArray.append(myData2["url"] as! String)
//print(myData2["url"] as! String)
}
else {
self.imageArray.append("\(#imageLiteral(resourceName: "property-placeholder-800x500"))")
}
/* ENd Get image 0 */
}
}
}
}catch {
//...
}
let meCount = (self.property.count)-1
/******** End Parse JSON **********/
//print(meCount)
if meCount != -1 {
}
else {
// Show alert view
let contactAddedAlert = UIAlertController(title: "Error: Check if Access Key is correct",
message: nil, preferredStyle: .alert)
contactAddedAlert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(contactAddedAlert, animated: true, completion: nil)
}
/******** Reload table View **********/
OperationQueue.main.addOperation({
self.tableView.reloadData()
self.refreshControl.endRefreshing()
}) }).resume()
}
/***********************************************************************************************/
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return property.count
}
/***********************************************************************************************/
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellFeatured") as! featuredTableViewCell
cell.addressLabel.text = property[indexPath.row].address
cell.cityNameLabel.text = property[indexPath.row].cityName
let imgURL = NSURL(string: imageArray[indexPath.row])
if imgURL != nil {
let data = NSData(contentsOf: (imgURL as URL?)!)
cell.imgView.image = UIImage(data: data! as Data)
}
return cell
}
}
答案 0 :(得分:8)
NSData(contentsOf: (imgURL as URL?)!)
是同步的。请参阅SDK文档:https://developer.apple.com/reference/foundation/nsdata/1547245-datawithcontentsofurl
哪个州:
Do not use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.
Instead, for non-file URLs, consider using the dataTaskWithURL:completionHandler: method of the NSURLSession class. See URL Session Programming Guide for details.
答案 1 :(得分:1)
您可以使用此窗格来提高速度 https://github.com/rs/SDWebImage 加载图片会很棒。