How to Use Swift Delegate Protocol to Show Data in The View Controller While Creating an iOS App?

swift delegate protocol example

In this iOS app tutorial, we will learn how to to use Swift Delegate Protocol in order to show data from one view controller to another while developing an iOS app.

This Swift delegate protocol tutorial for iOS is useful to those entrepreneurs who are looking to build an iOS app for their own startup.

We have two different methods to pass data from one view controller to another,

  1. Add target action on the button using custom target action
  2. Using Protocols and Delegates

Swift Delegate Protocol example

But we will suggest using protocol and delegates method as this is one of the easiest & suggestable ways to implement. Before jumping on to the implementation part, let’s first understand what is Protocol and what is Delegate in swift.

What is Protocol in Swift?

According to the Apple Swift Programming Language Guide, a Protocol is a powerful feature available in Swift Programming Language, used to define a “blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.”

These protocols in swift can be further adopted by a class, structure, or enumeration to provide an actual implementation of such requirements. Any of these types which satisfies the requirements of a protocol is said to conform to that protocol.

Swift keeps checking for protocol conformity issues at compile-time, allowing iOS developers to find some fatal glitches in the code even before running the program. Protocols allow iOS app developers to write resilient and extensible code in Swift language without having to adjust the language’s expressiveness.

What is Delegation in Swift?

Delegation in Swift refers to the design pattern that enables a class or structure to hand off some of its responsibilities to an instance of another type. Delegates are a design pattern that allows one object to send messages to another object when a specific event happens.

The delegation design pattern in swift is used for many things such as from handling table view events using UITableViewDelegate, to modifying the cache behaviour using NSCacheDelegate. The core purpose of the delegate design pattern is to allow an object to report back to its owner in a separate way.

Now, as we shared above that the protocol & delegation method is the most relevant & easiest way to pass data between view controllers, so let’s see how it works. This swift delegate example is created using Xcode 10.1 & Swift language 4.2.

Let’s See How to Pass Data using Swift Delegate Protocol

Step 1: Create a new application with the name “ProtocolDelegateDemo”

Create-new-application


Step 2: 
Create a User interface in main.storyboard like below.

Create-User-interface


Step 3:
Create a new file called “MovieTableViewCell.swift” and create a protocol

import UIKit

//MARK: protocol created
protocol MovieTableViewCellProtocol : class {
    func movieLiked(_ sender: MovieTableViewCell, isLiked: Bool)
}

Step 4: Create an outlet

//Table view cell components outlet created
class MovieTableViewCell: UITableViewCell {

    @IBOutlet weak var imgPoster: UIImageView!
    @IBOutlet weak var lblName: UILabel!
    @IBOutlet weak var lblReleaseDate: UILabel!
    @IBOutlet weak var btnLike: UIButton!
    @IBOutlet weak var btnUnlike: UIButton!

Step 5: Create a protocol object

// delegate variable create for protocol
    weak var delegate: MovieTableViewCellProtocol?
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

Step 6: Call protocol delegate method when user tap on like button

  //MARK: Call protocol method when user click on like button
    @IBAction func movieLiked(_ sender: UIButton) {
        delegate?.movieLiked(self, isLiked: true)
    }

Step 7: Call protocol delegate method when user tap on unlike button

//MARK: call protocol method when user click on unlike button
    @IBAction func movieUnliked(_ sender: UIButton) {
        delegate?.movieLiked(self, isLiked: false)
    }
}

Step 8: Movie information structure create in ViewController.swift

import UIKit

struct movieInformation {
    let poster: String
    let name: String
    let releaseDate: String
}

Step 9: Inherit MovieTableViewCellProtocol protocol

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, MovieTableViewCellProtocol {

    //MARK: tableview outlet created
    @IBOutlet weak var movieTableView: UITableView!
    
    // array of structure
    var movieInfo: [movieInformation] = []

    // movie details create
    var avengerDetail: movieInformation = movieInformation(poster: "avengers-4", name: "Avengers-4", releaseDate: "3 May 2019")
    var starwarsDetail: movieInformation = movieInformation(poster: "star-wars", name: "Star Wars: Episode IX", releaseDate: "20 December 2019")
    var wonderWomanDetail: movieInformation = movieInformation(poster: "wonder-woman", name: "Wonder Woman 2", releaseDate: "1 November 2019")
    
    //attributes for attributed string
    let myAttributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18)]
    
    override func viewDidLoad() {
        super.viewDidLoad()
     
        //movie details added into the array of structure
        movieInfo.append(avengerDetail)
        movieInfo.append(starwarsDetail)
        movieInfo.append(wonderWomanDetail)
        
        //tableview datasource and delegate method configure
        movieTableView.delegate = self
        movieTableView.dataSource = self
        
        movieTableView.allowsSelection = false
        
    }

Step 10: Configure tableview datasource methods

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

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MovieTableViewCell
        
        cell.imgPoster.image = UIImage(named: movieInfo[indexPath.row].poster)
        cell.lblName.text = movieInfo[indexPath.row].name
        cell.lblReleaseDate.text = movieInfo[indexPath.row].releaseDate
      
        cell.delegate = self
        return cell
    }

Step 11: Create a protocol delegate method

//MARK: check movie is like or unliked
    func movieLiked(_ sender: MovieTableViewCell, isLiked: Bool) {
        //fetch tapped indexpath
        guard let tappedIndexPath = movieTableView.indexPath(for: sender) else {
            return
        }
       
        //MARK: alert values set and call
        let alertTitle = NSMutableAttributedString(string: isLiked ? "Like" : "Unlike")
        
        let strLike = NSMutableAttributedString(string: isLiked ? "You liked " : "You disliked ")
        let strMovieName = NSMutableAttributedString(string: movieInfo[tappedIndexPath.row].poster, attributes: myAttributes)
        
        let strMovie = NSMutableAttributedString(string: " movie")

        strLike.append(strMovieName)
        strLike.append(strMovie)

        let alertMsg = strLike
        
	//MARK: selected cell fetch
        let cell = movieTableView.cellForRow(at: tappedIndexPath) as! MovieTableViewCell
        
        //MARK: set button image based on liked or unliked
        if isLiked {
            cell.btnLike.setImage(UIImage(named: "icon_liked"), for: .normal)
            cell.btnUnlike.setImage(UIImage(named: "icon_dislike"), for: .normal)
        } else {
            cell.btnUnlike.setImage(UIImage(named: "icon_disliked"), for: .normal)
            cell.btnLike.setImage(UIImage(named: "icon_like"), for: .normal)
        }

        displayAlert(title: alertTitle, msg: alertMsg)
    }

Step 12: Configure alert view controller

//MARK: setup alert controller
    func displayAlert(title: NSMutableAttributedString, msg: NSMutableAttributedString) {
        let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
        //alert.setValue(title, forKey: "attributedTitle")
        alert.setValue(msg, forKey: "attributedMessage")

        let action = UIAlertAction(title: "OK", style: .default, handler: nil)

        alert.addAction(action)

        present(alert, animated: true, completion: nil)
    }
}

And, done.

Now, let’s see the output


Conclusion

In the above swift protocol example, we learned how to show data in a view controller using swift delegation protocol. Though there are various ways to display data in view controller using protocol-oriented programming in swift given as,

  • when a segue is performed
  • using singletons
  • using the app delegate
  • assigning a delegate to a view controller
  • referencing a view controller directly
  • using the user defaults
  • with Swift closures

but the one we have used is the best & convenient to implement. This swift delegate protocol tutorial is useful for those who are looking to develop an iPhone app using such features to pass or fetch data.

Download the source code of this swift protocol tutorial via Github. In case, if you find it difficult to implement, feel free to hire iPhone app developers from Space-O. The consultation is free of cost.

This page was last edited on April 29th, 2019, at 7:46.
 
 

Have an App Idea?

Get your free consultation now

Leave a Reply

Your email address will not be published. Required fields are marked *