2015-08-16 1 views
1

J'essaie de configurer une page de flux avec UITableView, en récupérant toutes les données JSON de l'API Node.js.Swift - Renseigner UITableView avec les données de l'API

On dirait que cela fonctionne, mais il est très lent et parfois ne récupère pas toutes les images. Y a-t-il un moyen de le faire fonctionner complètement et d'optimiser le code?

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() 


    } 
} 

Répondre

1

Salut pour le chargement des images que vous pouvez utiliser SDWebImage il prendra soin de tous les soulever des objets lourds et la mise en cache pour vous. voici comment:

// 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 ...}]; 

Voici un Swift example

+0

Ajouté Un exemple rapide. Je vous conseille vraiment d'utiliser cette lib. –

+0

Pouvez-vous me donner un exemple d'utilisation liée à mon code? Merci – dpstart

+0

À l'intérieur de l'exemple rapide, vous pouvez voir. c'est juste ce dont tu as besoin. Vous importez la catégorie SDWebimagecache, puis vous l'utilisez avec l'URL et le bloc d'achèvement. C'est littéralement si facile. Dans votre cellule pour indexpath, activez-le sur les UIImageView et laissez-les gérer le chargement à l'aide de cette catégorie. –