Basic usage of Delegates in Network Calls.
- Create a Protocol for listening events occuring in Network functions.
protocol NetworkDelegate {
func didStartedAPICall()
func didFailedToGetResponse(error: String)
func didReceivedResponse(response: String)
func didEndAPICall()
}
- Create a Singleton class
NetworkManager
to manage networking in application.
- Add
delegate
property to assignNetworkDeleagate
properties.
class NetworkManager {
private init() {}
var delegate: NetworkDelegate?
static let shared = NetworkManager()
func fetch(urlString: String = "https://jsonplaceholder.typicode.com/users") {
delegate?.didStartedAPICall()
DispatchQueue.global(qos: .background).async {
URLSession.shared.dataTask(with: URL(string: urlString)!) { data, _, err in
if let error = err {
self.delegate?.didFailedToGetResponse(error: error.localizedDescription)
}
if let response = data, let asString = String(data: response, encoding: .utf8) {
self.delegate?.didReceivedResponse(response: asString)
}
self.delegate?.didEndAPICall()
}.resume()
}
}
}
- Conform to the
NetworkDelegate
in your desired View.
struct ContentView: View {
@State var data: [String] = ["π"]
var body: some View {
NavigationView {
...
.navigationBarTitle("Delegate Pattern").onAppear {
NetworkManager.shared.delegate = self
}
}
}
}
- Make Network call when tapping on buttons
- Here we are making two calls
- Success Call with
GET SUCCESS RESPONSE
Button - Failure Call with
GET FAILED RESPONSE
Button
- Success Call with
Button("GET SUCCESS RESPONSE") {
self.data.removeAll()
NetworkManager.shared.fetch()
}
Button("GET FAILED RESPONSE") {
self.data.removeAll()
NetworkManager.shared.fetch(urlString: "2398")
}
- Add the delegate functions and confirm to view
extension ContentView: NetworkDelegate {
func didReceivedResponse(response: String) {
data.append("β
GOT RESPONSE \n\(response)")
}
func didStartedAPICall() {
data.append("π¬ API CALL STARTED")
}
func didFailedToGetResponse(error: String) {
data.append("π API CALL ENDED WITH ERROR \n\(error)")
}
func didEndAPICall() {
data.append("π€ FINISHED API CALL")
}
}