这是我的网络服务层,我不知道我在哪里犯了错误,为什么它不让我正常地拔出它,帮助我弄清楚我的头脑
我在网络层遇到了麻烦:
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))
})
}
}--这是我的取款机--我需要从闭包Result获得数据
在我看来,我好像做错了什么,或者我不知道怎样才能在结束之后得到结果。
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>**
})
}
}发布于 2022-06-24 11:24:47
函数fetchGenericJsonData希望您做一些事情,然后用结果调用闭包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))
}https://stackoverflow.com/questions/72742731
复制相似问题