2017-02-17 93 views
0

我從一個json網址獲得了我的數據,但是當我想加載我的圖像時,它非常緩慢!加載圖像緩慢我的桌面視圖

class NewsTableViewController: UITableViewController { 

    var ids    = [String]() 
    var titles   = [String]() 
    var descriptions = [String]() 
    var images   = [String]() 
    var links   = [String]() 
    var dates   = [String]() 


    @IBOutlet var table_news: UITableView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     table_news.delegate = self 
     getNews() 

     // Uncomment the following line to preserve selection between presentations 
     // self.clearsSelectionOnViewWillAppear = false 

     // Uncomment the following line to display an Edit button in the navigation bar for this view controller. 
     // self.navigationItem.rightBarButtonItem = self.editButtonItem() 
    } 

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

    // MARK: - Table view data source 

    override func numberOfSections(in tableView: UITableView) -> Int { 
     // #warning Incomplete implementation, return the number of sections 
     return 1 
    } 

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     // #warning Incomplete implementation, return the number of rows 
     return self.ids.count 
    } 


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell:NewsTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "news_cell") as! NewsTableViewCell 


     cell.lbl_date.text = self.dates[indexPath.row] 
     cell.lbl_title.text = self.titles[indexPath.row] 

     var des = self.descriptions[indexPath.row] 

     if des.characters.count > 200 { 
      let range = des.rangeOfComposedCharacterSequences(for: des.startIndex..<des.index(des.startIndex, offsetBy: 200)) 
      let tmpValue = des.substring(with: range).appending("...") 

      cell.lbl_des.text = tmpValue 
     } 


     DispatchQueue.main.async{ 
      cell.img_news.setImageFromURl(stringImageUrl: self.images[indexPath.row]) 

     } 

     return cell 
    } 


    /* 
    // Override to support conditional editing of the table view. 
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { 
     // Return false if you do not want the specified item to be editable. 
     return true 
    } 
    */ 

    /* 
    // Override to support editing the table view. 
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
     if editingStyle == .delete { 
      // Delete the row from the data source 
      tableView.deleteRows(at: [indexPath], with: .fade) 
     } else if editingStyle == .insert { 
      // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
     }  
    } 
    */ 

    /* 
    // Override to support rearranging the table view. 
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { 

    } 
    */ 

    /* 
    // Override to support conditional rearranging of the table view. 
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { 
     // Return false if you do not want the item to be re-orderable. 
     return true 
    } 
    */ 

    /* 
    // MARK: - Navigation 

    // In a storyboard-based application, you will often want to do a little preparation before navigation 
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     // Get the new view controller using segue.destinationViewController. 
     // Pass the selected object to the new view controller. 
    } 
    */ 

    func getNews() { 
     RestApiManager.sharedInstance.getNews { (json: JSON) in 

      if let results = json.array { 
       for entry in results { 


        self.ids.append(entry["id"].string!) 
        self.titles.append(entry["title"].string!) 
        self.descriptions.append(entry["description"].string!) 
        self.images.append(entry["images"].string!) 
        self.links.append(entry["link"].string!) 
        self.dates.append(entry["date"].string!) 

       } 



       DispatchQueue.main.async{ 
        self.table_news.reloadData() 
       } 


      } 

     } 

    } 

} 

自定義單元格:

extension UIImageView{ 

    func setImageFromURl(stringImageUrl url: String){ 

     if let url = NSURL(string: url) { 
      if let data = NSData(contentsOf: url as URL) { 
       self.image = UIImage(data: data as Data) 
      } 
     } 
    } 
} 
class NewsTableViewCell: UITableViewCell { 



    @IBOutlet weak var img_news: UIImageView! 
    @IBOutlet weak var lbl_title: UILabel! 
    @IBOutlet weak var lbl_date: UILabel! 
    @IBOutlet weak var lbl_des: UILabel! 



    override func awakeFromNib() { 
     super.awakeFromNib() 
     // Initialization code 

     lbl_des.lineBreakMode = .byWordWrapping // or NSLineBreakMode.ByWordWrapping 
     lbl_des.numberOfLines = 0 
    } 

    override func setSelected(_ selected: Bool, animated: Bool) { 
     super.setSelected(selected, animated: animated) 

     // Configure the view for the selected state 
    } 

} 

我使用的是extension圖像視圖。

+1

http://stackoverflow.com/a/27712427/2303865 –

回答

0

爲你提的緩慢的問題是在UIImageView的擴展

extension UIImageView{ 

    func setImageFromURl(stringImageUrl url: String){ 

     if let url = NSURL(string: url) { 
      if let data = NSData(contentsOf: url as URL) { 
       self.image = UIImage(data: data as Data) 
      } 
     } 
    } 
} 

NSData(contentsOf: url as URL)您是從網絡同步檢索URL的內容,阻塞主線程。您可以使用帶有異步回調的NSURLSession或使用一些第三方庫(SDWebImage可能是最常用和經過測試的測試)來下載內容。