Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function with completion handler

Tags:

swift

I created the function below but I'm not sure how to call it, it complains saying:

Type 'T.Type' cannot conform to 'Decodable' 

Here's how I'd like to call it:

let result = getApiData(modelToDecode: MyModel, url: "abc")

This is what I've tried:

func getApiData<T : Decodable>(modelToDecode: T.Type, url: String) -> Any? {
    // I get an error below
    fetchDataAndDecode(url: String, modelToDecode: T.Type) { result in
    }

    // temp placeholder
    return nil
}

func fetchDataAndDecode<T : Decodable>(url: String, modelToDecode: T.Type, completionHandler: @escaping (Result<T.Type, NetworkError>) -> Void) {
    guard let url = URL(string: url) else {
        completionHandler(.failure(NetworkError.badURL))
        return
    }

    AF.request(url, method: .get).validate().responseData { response in
        guard let data = response.data else {
            completionHandler(.failure(NetworkError.apiFailed))
            return
        }

        do {
            // Decode the data
            let decodedData = try JSONDecoder().decode(modelToDecode.self, from: data)
            DispatchQueue.main.async {
                completionHandler(.success(decodedData as! T.Type))
            }
        } catch(let error) {
            print("🛑 Error on afRequest(): \(error)")
        }
    }
}

How can I call it inside the class properly?

like image 207
Arturo Avatar asked Jul 28 '26 20:07

Arturo


1 Answers

Result should be Result<T, NetworkError>. No need to add modelToDecode to your method declaration. You can explicitly set the resulting type in your async call. Btw you should the completion handler as well if you fail to decode your data:

enum NetworkError: Error {
    case badURL, apiFailed, corruptedData
}

Your method should look like this:

func fetchDataAndDecode<T: Decodable>(url: String, completionHandler: @escaping (Result<T, NetworkError>) -> Void) {
    guard let url = URL(string: url) else {
        completionHandler(.failure(.badURL))
        return
    }

    AF.request(url, method: .get).validate().responseData { response in
        guard let data = response.data else {
            completionHandler(.failure(.apiFailed))
            return
        }

        do {
            let decodedData = try JSONDecoder().decode(T.self, from: data)
            DispatchQueue.main.async {
                completionHandler(.success(decodedData))
            }
        } catch {
            completionHandler(.failure(.corruptedData))
        }
    }
}

And when calling it you need to explicitly set the resulting type:

fetchDataAndDecode(url: "yourURL") { (result: Result<WhatEver, NetworkError>) in 
    // switch the result here
}
like image 51
Leo Dabus Avatar answered Jul 30 '26 09:07

Leo Dabus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!