George Nhari
Code with C4

Code with C4

Loading/Downloading image from URL on Swift

George Nhari
·Dec 15, 2021·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • There are four ways to use SDWebImage in your project:
  • Installation with CocoaPods
  • Podfile
  • How to use

The easiest way I have found is using SDWebImage. I know you probably wanna do it on your own, but this library is popular as used by popular apps too. Here is a list

There are four ways to use SDWebImage in your project:

  • using CocoaPods
  • using Carthage
  • using Swift Package Manager
  • manual install (build frameworks or embed Xcode Project)

but I will just show cocoa pods, for the example

Installation with CocoaPods

CocoaPods is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries in your projects.

Podfile

platform :ios, '8.0'
pod 'SDWebImage', '~> 5.0'

How to use

import SDWebImage

imageView.sd_setImage(with: URL(string: "http://www.domain.com/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))

Using UIImageView+WebCache category with UITableView

Just import the UIImageView+WebCache.h header, and call the sd_setImageWithURL:placeholderImage: method from the tableView:cellForRowAtIndexPath: UITableViewDataSource method. Everything will be handled for you, from async downloads to caching management.

import SDWebImage

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    static let myIdentifier = "MyIdentifier"
    let cell = tableView.dequeueReusableCellWithIdentifier(myIdentifier, forIndexPath: indexPath) as UITableViewCell

    cell.imageView.sd_setImageWithURL(imageUrl, placeholderImage:placeholderImage)
    return cell
 
Share this