ios - 来自网络服务的图像在 UITableview 中刷新

标签 ios xcode swift

我试图将图像从网络服务加载到我的表格 View 中。但是图像被刷新并且相同的图像在每个单元格中旋转。我认为问题是由于没有以正确的方式实现缓存。我尝试了很多东西。但是没有运气..

导入 UIKit 类 NewsTableViewController: UITableViewController {

var SLAFImages = [String]()
var SLAFHeading = [String]()
var SLAFText = [String]()
var SLAFCount = [Int]()

@IBOutlet weak var btnAction: UIBarButtonItem!

override func viewDidLoad() {
    super.viewDidLoad()

    let reposURL = NSURL(string: "https://www.helitours.lk/test.html")
    // 2
    do{
        if let JSONData = NSData(contentsOfURL: reposURL!) {
            // 3
            if let json = try NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
                // 4
                if let reposArray = json["items"] as? [NSDictionary] {
                    // 5
                    for item in reposArray {
                       if let name = item.valueForKey("title") {

                           SLAFHeading.append(name as! String)
                        }

                        if let Imgname = item.valueForKey("main_image") {
                            let urlimg=("http://airforce.lk/"+(Imgname as! String)) as String;
                             SLAFImages.append(urlimg)
                                                       }
                                              }
                }
            }
        }

    }catch{}

    let infoImage = UIImage(named: "crest png.png")
    let imgWidth = infoImage?.size.width
    let imgHeight = infoImage?.size.height
    let button:UIButton = UIButton(frame: CGRect(x: 0,y: 0,width: imgWidth!, height: imgHeight!))
    button.setBackgroundImage(infoImage, forState: .Normal)
     //button.addTarget(self, action: Selector("openInfo"), forControlEvents: UIControlEvents.TouchUpInside)
    SLAFCount=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
    SLAFText = ["While they like to munch on underwater plants, you might ",
        "While they like to munch on underwater plants, you might ",
        "While they like to munch on underwater plants, you might "]

    //SLAFImages = ["Img1.jpg","Img2.jpg","Img3.jpg"]


    // 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 numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return 1
}

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


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell =
    self.tableView.dequeueReusableCellWithIdentifier(
        "NewsTableCell", forIndexPath: indexPath)
        as! NewsTableViewCell

    let row = indexPath.row
    cell.NewsHeading.font =
        UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
    cell.NewsHeading.text = SLAFHeading[row]
    if let url = NSURL(string: SLAFImages[row]) {
        let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, NSHTTPURLResponse, error) -> Void in

            if error != nil {
                print("thers an error in the log")
            } else {

                dispatch_async(dispatch_get_main_queue()) {
                    cell.NewsImage.image = UIImage(data: data!)

                }
            }

        }

        task.resume()
    }
    cell.NewsCount.text=String(SLAFCount[row])
    cell.layoutIfNeeded()
    return cell
}

最佳答案

在表格 View 单元格中下载图像

更好的方法 此代码不会增加应用程序的更多内存使用。

//Initialize your catch variable 
  var cache = NSCache()
    
// MARK: - Private   Image Download Block here
                private func downloadPhoto(url: NSURL, completion: (url: NSURL, image: UIImage) -> Void) {
                    dispatch_async(downloadQueue, { () -> Void in
                        if let data = NSData(contentsOfURL: url) {
                            if let image = UIImage(data: data) {
                                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                                    cache.setObject(image, forKey: url)
                                    completion(url: url, image: image)
                                })
                            }
                        }
                    })
                }
    


//Call this Function from Table view 
 //Step 1
 // Checking here Image inside Catch
           let imageurl = NSURL(string:”Image URL here”)
               let myimage = cache.objectForKey(imageurl!) as? UIImage
    
            //Step 2
            // Downloading here Promotion image
            if myimage == nil {
           downloadPhoto(imageurl!, completion: { (url, image) -> Void in
                    let indexPath_ = self.tblView.indexPathForCell(cell)
                            if indexPath.isEqual(indexPath_) {
                                cell.myImageView.image = image
                            }
                            
                        })
                        
                    }

希望对您有所帮助。

关于ios - 来自网络服务的图像在 UITableview 中刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37651515/

相关文章:

iphone - 如何使 UINavigationBar 不下推 View ?

html - 从 HTML 中提取 URL 并保留文本(如果有)

Swift:如何在 UICollectionView 单元格内嵌套具有不同表行数的 UITableView?

ios - 如何在 Swift 的横向模式下更改图标的旋转?

ios - 如何安全地尝试在 Swift 中执行 segue,同时忽略/手动处理可能的异常?

ios - Xcode - 使用导航栏按钮项和 Storyboard更改 View

ios - 在 Sqlite iOS 中找不到表

ios - 要在图像集中上传哪 3 个尺寸/分辨率图像以支持所有设备?

swift - "Cannot inherit from non-open class" swift

arrays - 修剪数组的有效方法