Swift5网络层和获取

发布于 2025-02-10 14:52:43 字数 3656 浏览 1 评论 0原文

这个我的网络服务层 我不明白我在哪里犯了一个错误,为什么它不允许我正常拔出它 帮助我弄清楚我的头

,我在网络层上遇到了麻烦:

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))
                })
        }
}

,这是我的fetcher 在这里,我需要从CLOSURE RESLURE&lt; t中获取数据,错误&gt;

在我看来,我在这里做错了什么,或者我不明白如何通过闭合来获得结果

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>**
                })
        }
}

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>**
                })
        }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅黛梨妆こ 2025-02-17 14:52:43

函数fetchgenericjsondata希望您做某事,然后以结果调用closture returndata。这样的事情:

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))
}

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))
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文