AboutContact

Protocol delegate in Swift: how to define and use a protocol function to handle external events

In this tutorial you'll learn with a basic example how to use a protocol in Swift to handle events coming from an external class. You'll see how to define a protocol function in Swift, how to the define the delegate of the protocol inside the class that will handle the protocol event. In this particular example we'll define an external function that download the data in an asynchronous way and call the protocol function as soon as the data are downloaded.

Let's start this tutorial by creating a new Swift iOS single view application. In this example we'll use the http unsecure connection. In iOS 9 this protocol is locked by default, we'll need to allow this kind of connection.

Right click on the info.plist file, click open as, select source code and add the following lines to allow the http protocol from your app.

<key>NSAppTransportSecurity</key>

<dict>

	<key>NSAllowsArbitraryLoads</key>

	<true/>

</dict>

Protocol definition: let's define the protocol function to handle events

Let's create now a new swift file. Here we'll define our protocol methods. Press on File, New, File, under iOS Source select Swift file and create it. I'll call definitions, but be free to name it as you like.

A protocol is defined with this format:

@objc protocol NAME OF THE PROTOCOL
{
	func name_of_the_events(data to pass:Type)
	optional func other_optional_function()
}

You can define the functions that will be handled by the delegate and the input parameters. You can also set the optional keywords, in order to tell swift that the function is not mandatory to implement.

The protocol that we'll define will handle the download events, for this reason we'll define a download_complete function. We can also define an error function, called when an error during the download process occurs.

@objc protocol get_data_delegate
{
    
	func download_complete(data: NSString)
    
	optional func error()

}

 

Download function definition

We'll now define the function that will download the data and call the protocol delegate when complete.

Let's create a new Swift iOS file (the same type as the previous one). I'll call functions, but be free to call it as you want.

Here is the definition of the function. It use the iOS asynchronous to download the data. As an input it has the link to call and the protocol that will handle the events. When we want to generate the external events, just call our protocol function.



func download_request_function(link:String,handler:get_data_delegate)
{
    let url:NSURL = NSURL(string: link)!
    
    let session = NSURLSession.sharedSession()
    
    let request = NSMutableURLRequest(URL: url)
    
    request.timeoutInterval = 10

    let task = session.dataTaskWithRequest(request) {
        (
        let data, let response, let error) in
        
        guard let _:NSData = data where error == nil else {
            if (handler.error != nil)
            {
                handler.error!()
            }
            return
        }
        
        let dataAsString = NSString(data: data!, encoding: NSUTF8StringEncoding)

        handler.download_complete(dataAsString!)
        
    }
    
    task.resume()
    
}

Implements the protocol delegate

It's now time to implements the delegate that will hadle the protocol events.

Open the ViewController.swift. On the top-right of the class name, add the name of the protocol. This will tell Swift that this class is a delegate of that protocol and will handle the event functions. In my case the name of the protocol is get_data_delegate.

class ViewController: UIViewController, get_data_delegate {

We need now to implement the event that will handle the events.

    func error()
    {
        print("error")
    }
    
    func download_complete(data: NSString)
    {
        print(data)
    }

To call the download_request_function we just need to send as input the link to download and the class istance that will handle the events, self in this case.

download_request_function(link_to_call, handler:self)

 

Here you can download the final project

 

 

 

Leave a comment








Comments


- 08 February 2016 at 07:57
Thanks a lot for this post, I had wasted lots of time to achieve this, but didn't succeed. Thanks for the post i understood my mistakes & finally achieved what i wanted.
Andrea - 09 February 2016 at 17:41
Happy that this tutorial helped you. If you need more tutorial,, be free to ask!
- 07 January 2016 at 23:06
Thank you very much! This has saved me a lot of hassle and helped me learn something new. I'm new to Swift and iOS coding but your site has certainly helped me already.





AboutContactPrivacy