ios - tableview 使应用程序变慢,并需要时间来获取数据 - swiftyJSON

标签 ios swift uitableview alamofire swifty-json

我正在尝试使用 swiftyJSON/Almofire 从 url 获取数据:

这是我的代码:

import UIKit
import Alamofire
import SwiftyJSON

 class NewsTableViewController: UITableViewController {


var arrRes = [[String:AnyObject]]() //Array of dictionary

override func viewDidLoad() {
    super.viewDidLoad()


    Alamofire.request(.GET, "myURL**").responseJSON { (responseData) -> Void in
        if((responseData.result.value) != nil) {
            let swiftyJsonVar = JSON(responseData.result.value!)
            print(swiftyJsonVar)
            if let resData = swiftyJsonVar[].arrayObject {
                self.arrRes = resData as! [[String:AnyObject]]
            }
            if self.arrRes.count > 0 {
                self.tableView.reloadData()
            }
        }
        }


    self.navigationController?.navigationBar.tintColor = UIColor(red:0.47, green:0.07, blue:0.55, alpha:1.00)

}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

   let cell = tableView.dequeueReusableCellWithIdentifier("bCell", forIndexPath: indexPath) as! TableViewCell

    var dict = arrRes[indexPath.row]

    if let strImage = arrRes[indexPath.row]["image"] as? String{
        if let data = NSData(contentsOfURL: NSURL(string:strImage.encodeUTF8()!)!) {
            cell.imgView.image = UIImage(data: data)
        }
    }


    cell.titleLabel?.text = dict["title"] as? String
    return cell

}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return arrRes.count
}

当我滚动时,tableview 变得很慢,获取数据需要时间!,你知道为什么它会这样吗, 我也遵循了这个教程,他没有提到他为什么在这里使用 Almofire,你怎么称呼从 JSON url 获取数据?它叫做“REST API”吗?所以我可以很好地搜索它,并且因为我是初学者所以有一个好的开始。

最佳答案

因为您在主线程中从 URL 获取图像:

        if let data = NSData(contentsOfURL: NSURL(string:strImage.encodeUTF8()!)!) {
            cell.imgView.image = UIImage(data: data)
        }

您应该在后台线程中执行此操作,当您将数据返回到主线程时:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
       if let data = NSData(contentsOfURL: NSURL(string:strImage.encodeUTF8()!)!) {
             dispatch_async(dispatch_get_main_queue(), ^{
                image = UIImage(data: data)
            });
        }
});

关于ios - tableview 使应用程序变慢,并需要时间来获取数据 - swiftyJSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38784717/

相关文章:

swift - (Swift) 如何更改单元格外的标签文本(事件发生的地方)?

ios - 在组的 subview 中设置辅助功能标签的顺序,通过 Voiceover 大声朗读?

iphone - 在表格 View 中插入图像?

swift - 如何在类型别名中使用类型参数?

Swift:dateFromString 的结果意外为 nil

ios - 如何使用 Swift 在 XCode 中制作带有动画的 LauchScreen?

ios - 如何在 XCode 中折叠 View Controller 的边缘

iOS CoreText 崩溃 : EXC_BAD_ACCESS KERN_INVALID_ADDRESS while setting view height

ios - 如何在 Swift 中获取任意数组的字节大小?

ios - 在 tableView 上拉动刷新