Skip to content

Commit

Permalink
improve http request helper
Browse files Browse the repository at this point in the history
  • Loading branch information
hiroshihorie committed Oct 31, 2023
1 parent 27b33d2 commit 0e06a60
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 32 deletions.
5 changes: 1 addition & 4 deletions Sources/LiveKit/Core/SignalClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -152,10 +152,7 @@ internal class SignalClient: MulticastDelegate<SignalClientDelegate> {

self.log("Validating with url: \(validateUrl)")

return HTTP().get(on: self.queue, url: validateUrl).then(on: self.queue) { data in
guard let string = String(data: data, encoding: .utf8) else {
throw SignalClientError.connect(message: "Failed to decode string")
}
return promise(from: HTTP.requestString, param1: validateUrl).then { string in
self.log("validate response: \(string)")
// re-throw with validation response
throw SignalClientError.connect(message: "Validation response: \"\(string)\"")
Expand Down
45 changes: 17 additions & 28 deletions Sources/LiveKit/Support/HTTP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,38 +17,27 @@
import Foundation
import Promises

internal class HTTP: NSObject, URLSessionDelegate {
internal class HTTP: NSObject {

private let operationQueue = OperationQueue()
private static let operationQueue = OperationQueue()

private lazy var session: URLSession = {
URLSession(configuration: .default,
delegate: self,
delegateQueue: operationQueue)
}()
private static let session: URLSession = URLSession(configuration: .default,
delegate: nil,
delegateQueue: operationQueue)

func get(on: DispatchQueue, url: URL) -> Promise<Data> {

Promise<Data>(on: on) { resolve, fail in

let request = URLRequest(url: url,
cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: .defaultHTTPConnect)

let task = self.session.dataTask(with: request) { data, _, error in
if let error = error {
fail(error)
return
}

guard let data = data else {
fail(NetworkError.response(message: "data is nil"))
return
}
public static func requestData(from url: URL) async throws -> Data {
let request = URLRequest(url: url,
cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: .defaultHTTPConnect)
let (data, _) = try await session.data(for: request)
return data
}

resolve(data)
}
task.resume()
public static func requestString(from url: URL) async throws -> String {
let data = try await requestData(from: url)
guard let string = String(data: data, encoding: .utf8) else {
throw InternalError.state(message: "Failed to convert string")
}
return string
}
}

0 comments on commit 0e06a60

Please sign in to comment.