Home > other >  Swift5 Network layer and fetch
Swift5 Network layer and fetch

Time:06-24

This my network Service layer I can’t understand where I made a mistake and why it doesn’t let me pull it out normally Result Help me figure out my head

And i have a trouble with network layer:

class NetworkService: Networking {
    func request(
        getURL: String,
        parameters: Dictionary<String, String>?,
        httpMethod: APIMethod,
        header: Dictionary<String, String>?,
        foregroundAPICall: Bool,
        debug: Bool,
        returnData: @escaping (_ result: Result<Data?, Error>) -> Void
    ) {
        
        guard let url = URL(string: getURL) else { return }
        var request = URLRequest(url: url)
        switch httpMethod {
        case .GET:
            request.httpMethod = httpMethod.description
            guard let headers = header else { return }
            for item in headers {
                request.addValue(item.key, forHTTPHeaderField: item.value)
            }
            break
        case .POST:
            request.httpMethod = httpMethod.description
            guard let headers = header else { return }
            for item in headers {
                request.addValue(item.key, forHTTPHeaderField: item.value)
            }
            request.httpBody = try? JSONSerialization.data(withJSONObject: parameters!, options: [])
            break
        }
        if httpMethod == .POST {
            let task = createDataTaskPost(
                with: request,
                complition: returnData
            )
            task.resume()  
        } 
    }
    private func createDataTaskPost(
        with request: URLRequest,
        complition: @escaping (_ result: Result<Data?, Error>) -> Void) -> URLSessionDataTask {
            return URLSession.shared.dataTask(
                with: request,
                completionHandler: { (data, response, error) in
                  
                    if let error = error {
                        complition(.failure(error))
                        return
                    }
                    guard let data = data else {  complition(.failure(ApiError.recieveNilBody))
                        return
                    }
                    complition(.success(data))
                })
        }
}

And here is my fetcher Here i need get the data from closure Result<T, Error>

It seems to me that I'm doing something wrong here, or I don't understand how I can get the result through closure

protocol DataFetcher {
    func fetchGenericJsonData<T: Codable>(
        urlString: String,
        parameters: Dictionary<String, String>?,
        httpMethod: APIMethod,
        foregroundAPICall: Bool,
        header: Dictionary<String, String>?,
        debug: Bool,
        returnData: @escaping (_ result: Result<[T?], Error>) throws -> Void
    )
}

public class NetworkDataFetcher: DataFetcher {
    var networking: Networking
    init(networking: Networking = NetworkService()) {
        self.networking = networking
    }
    func fetchGenericJsonData<T>(
        urlString: String,
        parameters: Dictionary<String, String>?,
        httpMethod: APIMethod,
        foregroundAPICall: Bool,
        header: Dictionary<String, String>?,
        debug: Bool,
        returnData: @escaping (_ result: Result<[T?], Error>) throws -> Void) {
            networking.request(
                getURL: urlString,
                parameters: parameters,
                httpMethod: httpMethod,
                header: header, foregroundAPICall: foregroundAPICall,
                debug: debug,
                returnData: { (data) in
                    **// Here i need get the data from closure Result<T, Error>**
                })
        }
}

CodePudding user response:

I figured out how to pull out the data now the problem is how to pull out an error

When I add this line try returnData(.failure(ApiError.failedParse)) to the catch method, it gives an error again

enter image description here

CodePudding user response:

The function fetchGenericJsonData expects you to do something, and then call the closure returnData with a result. Something like this:

func fetchGenericJsonData<T>(
    urlString: String,
    parameters: Dictionary<String, String>?,
    httpMethod: APIMethod,
    foregroundAPICall: Bool,
    header: Dictionary<String, String>?,
    debug: Bool,
    returnData: @escaping (_ result: Result<[T?], Error>) throws -> Void)
{
    // Do your network call. Then, if have a result, call:
    returnData(.success(value))
    // Or if you encountered an error:
    returnData(.failure(error))
}
  • Related