How to Create a Simple UIViewController for Displaying a Single Photo in iOS Development

Creating a Simple UIViewController for Displaying a Single Photo

When working with iOS development, it’s not uncommon to require displaying images within an app. While third-party frameworks like Three20 provide extensive functionality, sometimes a lightweight approach is more suitable.

Overview of the Problem

In this post, we’ll explore how to create a simple UIViewController that displays a single photo by downloading the image from a given URL and displaying it on a UIImageView. We’ll cover the technical aspects involved in achieving this goal.

Prerequisites for iOS Development

Before diving into this tutorial, ensure you have:

  • Xcode installed on your computer
  • Basic knowledge of Swift (the programming language used for iOS development)
  • Familiarity with iOS development concepts and frameworks

Creating a Simple UIViewController for Displaying a Single Photo

Step 1: Create a New UIViewController Class

Create a new UIViewController subclass to manage the image display. Let’s call it PhotoViewController.

{<
import UIKit

class PhotoViewController: UIViewController {

    // MARK: - Properties

    let imageView = UIImageView()

    var url: URL?

    // MARK: - Lifecycle Methods

    override func viewDidLoad() {
        super.viewDidLoad()
        setupImageView()
    }

    // MARK: - Setup Methods

    func setupImageView() {
        view.addSubview(imageView)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            imageView.widthAnchor.constraint(equalToConstant: 200),
            imageView.heightAnchor.constraint(equalToConstant: 200)
        ])
    }

}
>

Step 2: Initialize the UIViewController with a URL

In this step, we’ll initialize our PhotoViewController instance with a given URL. We’ll use the URL to download the image and display it on our UIImageView.

{<
import UIKit

class PhotoViewController: UIViewController {

    // MARK: - Properties

    let imageView = UIImageView()
    var url: URL?

    // MARK: - Lifecycle Methods

    override func viewDidLoad() {
        super.viewDidLoad()
        setupImageView()
    }

    // MARK: - Setup Methods

    func setupImageView() {
        view.addSubview(imageView)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            imageView.widthAnchor.constraint(equalToConstant: 200),
            imageView.heightAnchor.constraint(equalToConstant: 200)
        ])

        // Initialize the URL to display an image from a given URL
        url = URL(string: "https://example.com/image.jpg")
    }

}
>

Step 3: Downloading and Displaying the Image

To download the image, we’ll use Swift’s built-in URLSession class. We’ll create a function to download the image from a given URL, convert it to a UIImage, and display it on our UIImageView.

{<
import UIKit
import URLSession

class PhotoViewController: UIViewController {

    // MARK: - Properties

    let imageView = UIImageView()
    var url: URL?

    // MARK: - Lifecycle Methods

    override func viewDidLoad() {
        super.viewDidLoad()
        setupImageView()
    }

    // MARK: - Setup Methods

    func setupImageView() {
        view.addSubview(imageView)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            imageView.widthAnchor.constraint(equalToConstant: 200),
            imageView.heightAnchor.constraint(equalToConstant: 200)
        ])

        // Initialize the URL to display an image from a given URL
        url = URL(string: "https://example.com/image.jpg")
    }

    func downloadAndDisplayImage() {
        guard let url = url else { return }

        URLSession.shared.dataTask(with: url) { [self] data, response, error in
            if let error = error {
                print("Error downloading image: \(error)")
                return
            }

            guard let data = data else { return }

            do {
                // Convert the downloaded data to a UIImage
                let image = UIImage(data: data)

                // Display the image on our UIImageView
                self.imageView.image = image

            } catch {
                print("Error displaying image: \(error)")
            }
        }.resume()
    }

}
>

Interaction-Safe Downloading of Images

As mentioned in the initial response, it’s recommended to download images on a separate thread to ensure interaction safety. To achieve this, we can use Swift’s DispatchQueue class.

{<
import UIKit
import URLSession

class PhotoViewController: UIViewController {

    // MARK: - Properties

    let imageView = UIImageView()
    var url: URL?

    // MARK: - Lifecycle Methods

    override func viewDidLoad() {
        super.viewDidLoad()
        setupImageView()
    }

    // MARK: - Setup Methods

    func setupImageView() {
        view.addSubview(imageView)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            imageView.widthAnchor.constraint(equalToConstant: 200),
            imageView.heightAnchor.constraint(equalToConstant: 200)
        ])

        // Initialize the URL to display an image from a given URL
        url = URL(string: "https://example.com/image.jpg")
    }

    func downloadAndDisplayImage() {
        guard let url = url else { return }

        URLSession.shared.dataTask(with: url) { [self] data, response, error in
            if let error = error {
                print("Error downloading image: \(error)")
                return
            }

            guard let data = data else { return }

            do {
                // Convert the downloaded data to a UIImage
                let image = UIImage(data: data)

                // Display the image on our UIImageView
                self.imageView.image = image

            } catch {
                print("Error displaying image: \(error)")
            }
        }.resume()

        // Use DispatchQueue to download images in a separate thread
        DispatchQueue.global(qos: .utility).async {
            self.downloadAndDisplayImage()
        }
    }

}
>

Conclusion

In this tutorial, we’ve explored how to create a simple UIViewController that displays a single photo by downloading the image from a given URL and displaying it on a UIImageView. We’ve covered the technical aspects involved in achieving this goal, including using URLSession, converting downloaded data to a UIImage, and interaction-safe downloading of images.

Step-by-Step Solution

To create a simple UIViewController for displaying a single photo:

  1. Create a new UIViewController subclass.
  2. Initialize the view controller with a given URL.
  3. Download the image from the URL using URLSession.
  4. Convert the downloaded data to a UIImage.
  5. Display the image on the view controller’s UIImageView.

By following these steps, you can create your own simple UIViewController for displaying a single photo without relying on third-party frameworks like Three20.


Last modified on 2025-04-04