Updated 6 February 2024
In this article you will learn about Use Callbacks in Swift in Place of Delegates.
In Swift, a callback refers to a mechanism where a function or a piece of code is passed as an argument to another function. The function receiving the callback can the execute the provided code at a later time or under certain conditions.
Callback are often used to handle asynchronous operation, such as network request, animation, or other task that don’t complete immediately.
There are different ways to implement callbacks in Swift, but we saw callback through closure here.
You may also check our Flutter App development services.
You can use closures to define a block of code that can be passed around and executed later.
In Swift closure callback refers to the use of closure as a mechanism for handling asynchronous or events. Callback are often employed to notify the completion of a task or handle the result of an asynchronous operations.
Closers can be passed as argument to functions, allowing you to define a block of code that gets executed at a later time when a specific condition met.
Before working on Callback, you need to follow below steps.
This this implementation we will use Alamofire to Api Calling .
First of all we need to create a new project where you will implement Callback in Swift in Place of Delegate.
After that you need to create a class for calling your network request by name NetworkManager
1 2 3 4 5 6 7 |
import Foundation import Alamofire import SwiftyJSON class NetworkManager: NSObject{ } |
After that you need to create function in class NetworkManager to which you want to send Network Request.
1 2 3 |
func fetchData(params : String, dict: [String: Any] , _ completion: @escaping ServiceResponse) -> Void { } |
ServiceResponse is a typealias which will contain your response and error.
1 2 |
typealias ServiceResponse = (JSON?, Error?) -> Void |
In this steps we will write below mention code inside fetchData() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
var baseURLString: String = "" // Add your base url here func fetchData(params : String, dict: [String: Any] , _ completion: @escaping ServiceResponse) -> Void { var baseURLWithAPIKeyString = "\(self.baseURLString)" var url = baseURLWithAPIKeyString var flag :Int = 0 for (key, value) in dict { if(flag == 0){ url += "?\(key)=\(value)" flag = 1 }else{ url += "&\(key)=\(value)" } } var requestURL: String = url print(requestURL) var request1 = URLRequest(url: URL(string : requestURL)!) request1.httpMethod = "GET" request1.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData let manager = Alamofire.SessionManager.default manager.request(request1).responseJSON { (response) in switch response.result { case .success: let jsonData = try! JSON.init(data: response.data!) print(jsonData) completion(jsonData, nil) case .failure(let error): completion(nil , error as NSError) } } } |
In this steps we will send request from our ViewController class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import UIKit import SwiftyJSON class ViewController: UIViewController { var params = "" let networkManager = NetworkManager() var dict1 = [String: Any]() override func viewDidLoad() { super.viewDidLoad() networkManager.fetchData(params: params, dict: dict1) { (responseObject: JSON?, error: Error?) in if (error != nil) { print("You call back data --->",error) print("Error logging you in!") } else { print("Your call back data -->",responseObject!) print("Do some thing") } } } } |
In responseObject, you will get your data using this Callback.
In this article we have discussed about Use Callbacks in Swift.
I hope this blog is helpful to understand Callbacks.
Thanks for reading this blog. You can also check other blogs from here for more knowledge.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.