Fix Linux networking

This commit is contained in:
Christoph Hagen 2022-06-09 16:27:37 +02:00
parent 9654da1d4f
commit e8c7147e2f

View File

@ -145,41 +145,12 @@ public final class PushClient {
var request = URLRequest(url: server.appendingPathComponent(route.rawValue)) var request = URLRequest(url: server.appendingPathComponent(route.rawValue))
request.httpBody = bodyData request.httpBody = bodyData
request.httpMethod = "POST" request.httpMethod = "POST"
return await post(request)
if #available(iOS 15.0, *) {
return await post(request)
} else {
return await withCheckedContinuation { continuation in
postRequest(request) { data in
continuation.resume(returning: data)
}
}
}
} }
private func postRequest(_ request: URLRequest, completion: @escaping (Data?) -> Void) {
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Failed with error: \(error)")
completion(nil)
}
guard let httpResponse = response as? HTTPURLResponse else {
completion(nil)
return
}
guard httpResponse.statusCode == 200 else {
print("Failed with code: \(httpResponse.statusCode)")
completion(nil)
return
}
completion(data)
}.resume()
}
@available(iOS 15.0, *)
private func post(_ request: URLRequest) async -> Data? { private func post(_ request: URLRequest) async -> Data? {
do { do {
let (data, response) : (Data, URLResponse) = try await URLSession.shared.data(for: request) let (data, response) : (Data, URLResponse) = try await data(for: request)
guard let httpResponse = response as? HTTPURLResponse else { guard let httpResponse = response as? HTTPURLResponse else {
return nil return nil
} }
@ -194,8 +165,37 @@ public final class PushClient {
} }
} }
private func data(for request: URLRequest) async throws -> (Data, URLResponse) {
#if !canImport(FoundationNetworking)
if #available(iOS 15.0, *) {
return try await URLSession.shared.data(for: request)
}
#endif
return try await URLSession.shared.dataRequest(request)
}
private func hash(_ masterKey: String) -> Data { private func hash(_ masterKey: String) -> Data {
Data(SHA256.hash(data: masterKey.data(using: .utf8)!)) Data(SHA256.hash(data: masterKey.data(using: .utf8)!))
} }
} }
private extension URLSession {
func dataRequest(_ request: URLRequest) async throws -> (Data, URLResponse) {
try await withCheckedThrowingContinuation { continuation in
dataTask(with: request) { data, response, error in
if let error = error {
print("Failed with error: \(error)")
continuation.resume(throwing: error)
return
}
guard let data = data, let response = response else {
continuation.resume(throwing: URLError(.unknown))
return
}
continuation.resume(returning: (data, response))
}.resume()
}
}
}