我正在尝试使用 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/