2017-05-02 7 views
1

URLからの画像を表示するはずのこのコードがあります。私は画像の数とimagesを印刷すると、私は7つの画像の配列を取得するので、すべてが良いと思う。UITableViewはURLから画像を表示しません

私のコードを見て、間違いをどこで修正してください。

import UIKit 
import SwiftyJSON 
import Haneke 

class SlideViewController: UIViewController , UITableViewDelegate ,  UITableViewDataSource { 

@IBOutlet weak var tableview : UITableView! 

var images = [String]() 
    override func viewDidLoad() { 
    super.viewDidLoad() 

    tableview.delegate = self 
    tableview.dataSource = self 
    getJSON() 

} 


func numberOfSections(in tableView: UITableView) -> Int { 
    return 0 
} 


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return images.count 
} 



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell", for: indexPath) as! ImageTableViewCell 

    let remote = images[indexPath.row] 

    let imageurl = URL(string: remote) 
    cell.images.sd_setImage(with: imageurl) 


    return cell 
} 

func getJSON() { 

    let url = "http://localhost:8000/api/hello" 
    let myuel = URL(string: url) 
    let resquest = NSMutableURLRequest(url: myuel!) 

    resquest.httpMethod = "GET" 


    let task = URLSession.shared.dataTask(with: resquest as URLRequest, completionHandler: { data,response,error in 
     if error != nil{ 
      print(error!.localizedDescription) 
      return 
     } 

     let json = JSON(data) 

     self.images = json["pic"].arrayObject! as! [String] 
     print(self.images.count) 
     print(self.images) 


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

    }) 
    task.resume() 
    } 


    } 
+0

SDWebimageを使用する方がURLを受け取り、画像を表示する方が良いです。 –

+0

api呼び出しにlocalhostを使用しているので、イメージURLがlocalhostからのものではないことを確認してください。 –

+0

次のビューで私はlocalhostから画像を使用しています。 – leo0019

答えて

0

URLから画像をロードし、表示するために使用この拡張機能を以下の方法からセクションを返すことを確認し、

func numberOfSections(in tableView: UITableView) -> Int { 
    return 1 
} 

非同期

extension UIImageView { 
    public func imageFromServerURL(urlString: String) { 

     URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in 

      if error != nil { 
       print(error) 
       return 
      } 
      DispatchQueue.main.async(execute: {() -> Void in 
       let image = UIImage(data: data!) 
       self.image = image 
      }) 

     }).resume() 
    }} 

に画像をロードするための延長上で使用このようなimageView。

cell.imageview.imageFromServerURL(urlString: urlString) 
関連する問題