我正在尝试从url获取数据,使用swiftyJSON/almodere:
这是我的代码:

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/

10-10 01:11
查看更多