ios - Swift - 使用来自 API 的数据填充 UITableView

标签 ios swift uitableview api data-retrieval

我正在尝试使用 UITableView 设置提要页面,从 Node.js API 检索所有 JSON 数据。

看起来它正在工作,但速度很慢,有时无法检索所有图像。有没有办法让它完全工作,并优化代码?

import UIKit




class homeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {



@IBOutlet weak var tableView: UITableView!


var jsonData : [NSDictionary] = [NSDictionary]()
var imageUrls: NSDictionary = NSDictionary()
var urlsArray: [NSURL]! = [NSURL]()


override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.reloadData()

    let qualityOfServiceClass = QOS_CLASS_BACKGROUND
    let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
    dispatch_async(backgroundQueue, {
        println("This is run on the background queue")
        self.refreshData()
        self.getImage()

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            println("This is run on the main queue, after the previous code in outer block")
            self.tableView.reloadData()
        })
    })




}

override func viewWillAppear(animated: Bool) {



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}





func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


   return jsonData.count



}



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


    var type = jsonData[indexPath.row]["type"] as! Int

    if type == 1 {


        println("Type= \(type)")

        let cell1 : cellTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! cellTableViewCell


        //If images url are retrieved, load them. Otherwise, load the placeholders
        if self.urlsArray.isEmpty == false {

            println("Tiè: \(self.urlsArray[indexPath.row])")


            if let data = NSData(contentsOfURL: self.urlsArray[indexPath.row]) {

                    cell1.profileImg?.image = UIImage(data: data)

                }

        } else {

            cell1.profileImg?.image = UIImage(named: "placeholder.png")

        }


        cell1.testLbl.text = (self.jsonData[indexPath.row]["author"] as? String)!

        return cell1

    } else {


        let cell2 : cell2TableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell2") as! cell2TableViewCell


        return cell2
    }
}


func refreshData()   {


    let requestURL = NSURL(string:"http://adall.ga/api/feeds/author/mat/0")!


    var request = NSMutableURLRequest(URL: requestURL)
    request.HTTPMethod = "GET"



    request.addValue(userToken, forHTTPHeaderField: "tb-token")

    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithRequest(request) {
        data, response, error in


        println(response)

        var dataString = NSString(data: data, encoding: NSUTF8StringEncoding)

        println(dataString)

        //let jsonResult : NSDictionary = (NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary)!
        //jsonData = (NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers , error: nil) as? NSArray)!


        self.jsonData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as! [NSDictionary]



    }

    task.resume()

    var index: Int
    for index = 0; index < 10000; ++index {
        print("Index: \(index), Task state: \(task.state)")
    }
}



func getImage() {

    var i = 0

    for jsonSingleData in jsonData {

        let author = jsonSingleData["author"] as! String


        let requestURL2 = NSURL(string: "http://adall.ga/api/users/" + author + "/image")!

        println("request: \(requestURL2)")


        var request2 = NSMutableURLRequest(URL: requestURL2)
        request2.HTTPMethod = "GET"


        request2.addValue(userToken!, forHTTPHeaderField: "tb-token")


        let session2 = NSURLSession.sharedSession()

        let task2 = session2.dataTaskWithRequest(request2) {
            data, response, error in


            println("response= \(response)")


            var dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
            println(dataString)



            self.imageUrls = (NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary)


            //check if exists
            let imageUrl = self.imageUrls["url"] as! String

            let url = NSURL(string: "http://" +  imageUrl)

            self.urlsArray.append(url!)

            println(self.urlsArray)


            }

        task2.resume()


    }
}

最佳答案

您好,您可以使用 SDWebImage 加载图像它将为您处理所有繁重的工作和缓存。方法如下:

// Here we use the new provided sd_setImageWithURL: method to load the web image
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]
                             completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {... completion code here ...}];

这是一个 Swift example

关于ios - Swift - 使用来自 API 的数据填充 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32034342/

相关文章:

ios - 我如何知道 handleOpenURL 响应的文档类型?

ios - 如何在 iOS 上报告 Firebase 崩溃的非致命异常?

uitableview - UIView-Encapsulated-Layout-Width/Height 约束为零

swift - 按子查询 Firebase 数据

ios - 一次插入两个部分

ios - 如何使用 UITableViews 深入查看 plist?

ios - 使用 Storyboard ios7 在选项卡栏 Controller 中设置所选图像

ios - NSFetchedResultsController 看不到插入(或更新)

ios - Sprite 的圆形路径?

facebook - 试图从 Facebook 获取用户生日,但我没有得到。我究竟做错了什么?