Skip to content

Commit 7961572

Browse files
committed
Make iOS HTTP bridge return synchronously
1 parent 89c8227 commit 7961572

1 file changed

Lines changed: 13 additions & 6 deletions

File tree

apple/swiftui/BonsaiNativeSwiftUI.swift

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3453,9 +3453,11 @@ public func bonsai_native_swiftui_http_send_json(
34533453
request.httpBody = Data(body.utf8)
34543454
}
34553455

3456+
let semaphore = DispatchSemaphore(value: 0)
3457+
var result: (Bool, String) = (false, "request did not complete")
3458+
34563459
URLSession.shared.dataTask(with: request) { data, response, error in
34573460
let responseBody = data.flatMap { String(data: $0, encoding: .utf8) } ?? ""
3458-
let result: (Bool, String)
34593461
if let error {
34603462
result = (false, error.localizedDescription)
34613463
} else if let httpResponse = response as? HTTPURLResponse,
@@ -3468,12 +3470,17 @@ public func bonsai_native_swiftui_http_send_json(
34683470
result = (true, responseBody)
34693471
}
34703472

3471-
DispatchQueue.main.async {
3472-
result.1.withCString { pointer in
3473-
callback?(context, result.0, pointer)
3474-
}
3475-
}
3473+
semaphore.signal()
34763474
}.resume()
3475+
3476+
let timeout = timeoutSeconds > 0 ? timeoutSeconds : 30
3477+
if semaphore.wait(timeout: .now() + timeout) == .timedOut {
3478+
result = (false, "Request timed out")
3479+
}
3480+
3481+
result.1.withCString { pointer in
3482+
callback?(context, result.0, pointer)
3483+
}
34773484
}
34783485

34793486
@_cdecl("bonsai_native_swiftui_set_padding")

0 commit comments

Comments
 (0)