comment implémenter le chargement paresseux des images dans la vue de table en utilisant swift

Je veux utiliser le concept de chargement paresseux pour ma vue de table en utilisant swift. Dans ma vue de table, je montre plusieurs cellules qui contiennent des images de produits et le nom du produit. Aidez-moi s'il vous plaît à get la solution.

Ancienne solution:

Puisque vous n'affichez aucun code.

Voici l'exemple pour vous.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // try to reuse cell let cell:CustomCell = tableView.dequeueReusableCellWithIdentifier("DealCell") as CustomCell // get the deal image let currentImage = deals[indexPath.row].imageID let unwrappedImage = currentImage var image = self.imageCache[unwrappedImage] let imageUrl = NSURL(ssortingng: "http://staging.api.cheapeat.com.au/deals/\(unwrappedImage)/photo") // reset reused cell image to placeholder cell.dealImage.image = UIImage(named: "placeholder") // async image if image == nil { let request: NSURLRequest = NSURLRequest(URL: imageUrl!) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in if error == nil { image = UIImage(data: data) self.imageCache[unwrappedImage] = image dispatch_async(dispatch_get_main_queue(), { cell.dealImage.image = image }) } else { } }) } else{ cell.dealImage.image = image } return cell } 

Suivez ce tutoriel pour plus d'informations. J'espère que ceci vous aidera.

Nouvelle solution

Voici une extension pour elle qui est créée par mon ami Leo Dabus qui est vraiment simple à utiliser:

 extension UIImageView { func downloadImageFrom(link link:Ssortingng, contentMode: UIViewContentMode) { NSURLSession.sharedSession().dataTaskWithURL( NSURL(ssortingng:link)!, completionHandler: { (data, response, error) -> Void in dispatch_async(dispatch_get_main_queue()) { self.contentMode = contentMode if let data = data { self.image = UIImage(data: data) } } }).resume() } } 

Maintenant, dans votre méthode cellForRowAtIndexPath , affectez l'image à la cellule de cette façon:

 cell.cellImageView.image = UIImage(named: "placeholder") //set placeholder image first. cell.cellImageView.downloadImageFrom(link: imageLinkArray[indexPath.row], contentMode: UIViewContentMode.ScaleAspectFit) //set your image from link array. 

Et comme Rob suggéré dans le commentaire voici quelques bibliothèques utiles que vous pouvez utiliser:

  1. https://github.com/Alamofire/AlamofireImage
  2. https://github.com/onevcat/Kingfisher
  3. https://github.com/rs/SDWebImage
  4. https://github.com/kean/DFImageManager

Comme je ne peux pas encore commenter, voici une version de Swift 3 (Xcode 8 Beta 6) de l'extension utile fournie par Leo Dabus.

 extension UIImageView { func downloadImageFrom(link:Ssortingng, contentMode: UIViewContentMode) { URLSession.shared.dataTask( with: NSURL(ssortingng:link)! as URL, completionHandler: { (data, response, error) -> Void in DispatchQueue.main.async { self.contentMode = contentMode if let data = data { self.image = UIImage(data: data) } } }).resume() } } 

J'utilise ceci à l'intérieur d'une class qui remplit la cellule de la table, cela fonctionne très bien dans ce context, juste au cas où les newbs se requestraient si ça va:

 albumArt.image = UIImage(named: "placeholder") albumArt.downloadImageFrom(link: "http://someurl.com/image.jpg", contentMode: UIViewContentMode.scaleAspectFit) 

Tâche

Chargement d'image asynchronous dans tableViewCell dans swift 3 en utilisant SDWebImage.

Détails

xCode 8.3.1, swift 3.1

Échantillon complet

Info.plist (append de la valeur)

 <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> 

Podfile

  platform :ios, '8.0' use_frameworks! target 'stackoverflow-28694645' do pod 'Alamofire' pod 'ObjectMapper' pod 'SDWebImage' end 

Gestionnaire de réseau

 import Foundation import Alamofire // data loader class NetworkManager { class func request(ssortingng: Ssortingng, block: @escaping ([Ssortingng: Any]?)->()) { Alamofire.request(ssortingng).responseJSON { response in if let result = response.result.value as? [Ssortingng: Any] { block(result) } else { block(nil) } } } } 

ItunceItem

 import Foundation import ObjectMapper class ItunceItem: Mappable { var wrapperType: Ssortingng? var imageUrlSsortingng:Ssortingng? required convenience init?(map: Map) { self.init() } private func unwrapedDescription(value: Any?) -> Ssortingng { if let value = value { return "\(value)" } return "[no data]" } var description: Ssortingng { var _result = "" _result += " imageUrlSsortingng: \(unwrapedDescription(value: imageUrlSsortingng))\n" _result += " wrapperType: \(unwrapedDescription(value: wrapperType))\n" _result += " price: " return _result } func mapping(map: Map) { wrapperType <- map["wrapperType"] imageUrlSsortingng <- map["artworkUrl100"] } } 

TableViewCell

 import UIKit class TableViewCell: UITableViewCell { @IBOutlet weak var artworkImageView: UIImageView! } 

ViewController

 import UIKit import SDWebImage class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! fileprivate var items = [ItunceItem]() fileprivate var viewControlerInited = false override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableView.tableFooterView = UIView() reloadData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) viewControlerInited = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) disableDownloadingAllImages() } } // MARK: - Different extension ViewController { fileprivate func reloadData() { NetworkManager.request(ssortingng: "https://itunes.apple.com/search?term=navigator") { [weak self] json in if let _self = self { if let json = json, let array = json["results"] as? [[Ssortingng:Any]] { var result = [ItunceItem]() for item in array { if let itunceItem = ItunceItem(JSON: item) { result.append(itunceItem) } } _self.items = result _self.tableView.reloadData() } } } } fileprivate func disableDownloadingAllImages() { SDWebImageDownloader.shared().cancelAllDownloads() } fileprivate func reloadImages() { for cell in tableView.visibleCells { if let indexPath = tableView.indexPath(for: cell) { let cell = cell as! TableViewCell if let imageUrlSsortingng = items[indexPath.row].imageUrlSsortingng, let url = URL(ssortingng: imageUrlSsortingng) { cell.artworkImageView.sd_cancelCurrentAnimationImagesLoad() cell.artworkImageView.sd_setImage(with: url) } } } } } // MARK: - UITableViewDataSource extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell return cell } } // MARK: - UITableViewDelegate extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let cell = cell as! TableViewCell if let imageUrlSsortingng = items[indexPath.row].imageUrlSsortingng, let url = URL(ssortingng: imageUrlSsortingng) { cell.artworkImageView.sd_setImage(with: url) } } func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { let cell = cell as! TableViewCell cell.artworkImageView.sd_cancelCurrentImageLoad() } } 

Main.storyboard

 <?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12120" systemVersion="16E195" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r"> <device id="retina4_7" orientation="portrait"> <adaptation id="fullscreen"/> </device> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12088"/> <capability name="Constraints to layout margins" minToolsVersion="6.0"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--View Controller--> <scene sceneID="tne-QT-ifu"> <objects> <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_28694645" customModuleProvider="target" sceneMemberID="viewController"> <layoutGuides> <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/> <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/> </layoutGuides> <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="130" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="cY7-zo-hDK"> <rect key="frame" x="0.0" y="20" width="375" height="647"/> <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> <prototypes> <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="TableViewCell" id="HDb-wV-LQ8" customClass="TableViewCell" customModule="stackoverflow_28694645" customModuleProvider="target"> <rect key="frame" x="0.0" y="28" width="375" height="130"/> <autoresizingMask key="autoresizingMask"/> <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="HDb-wV-LQ8" id="Gky-9l-DJ9"> <rect key="frame" x="0.0" y="0.0" width="375" height="129.5"/> <autoresizingMask key="autoresizingMask"/> <subviews> <imageView userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="YX7-DV-Qnj"> <rect key="frame" x="137" y="14" width="100" height="100"/> <constraints> <constraint firstAtsortingbute="width" constant="100" id="p8R-if-uRk"/> </constraints> </imageView> </subviews> <constraints> <constraint firstItem="YX7-DV-Qnj" firstAtsortingbute="centerY" secondItem="Gky-9l-DJ9" secondAtsortingbute="centerY" id="Lg1-9u-aL6"/> <constraint firstItem="YX7-DV-Qnj" firstAtsortingbute="top" secondItem="Gky-9l-DJ9" secondAtsortingbute="topMargin" constant="6" id="kqB-PW-PE1"/> <constraint firstItem="YX7-DV-Qnj" firstAtsortingbute="centerX" secondItem="Gky-9l-DJ9" secondAtsortingbute="centerX" id="lKR-7v-WtO"/> </constraints> </tableViewCellContentView> <connections> <outlet property="artworkImageView" destination="YX7-DV-Qnj" id="spC-sk-Al3"/> </connections> </tableViewCell> </prototypes> </tableView> </subviews> <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <constraints> <constraint firstItem="cY7-zo-hDK" firstAtsortingbute="top" secondItem="y3c-jy-aDJ" secondAtsortingbute="bottom" id="J7x-rb-aus"/> <constraint firstItem="cY7-zo-hDK" firstAtsortingbute="leading" secondItem="8bC-Xf-vdC" secondAtsortingbute="leading" id="Zgh-3u-vEw"/> <constraint firstItem="cY7-zo-hDK" firstAtsortingbute="bottom" secondItem="wfy-db-euE" secondAtsortingbute="top" id="v68-ej-1ne"/> <constraint firstAtsortingbute="trailing" secondItem="cY7-zo-hDK" secondAtsortingbute="trailing" id="ywW-Jl-d9z"/> </constraints> </view> <connections> <outlet property="tableView" destination="cY7-zo-hDK" id="6rX-DT-7Va"/> </connections> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="-76" y="116.49175412293854"/> </scene> </scenes> </document> 

Résultat

entrez la description de l'image ici