Skip to navigation

Listen to Client Side Messages on Swift (iOS)

WebView Handler Name Requirement

When registering your WKWebView message handler, the name must be exactly "ReactNativeWebView". The Coinflow checkout page checks for window.webkit.messageHandlers.ReactNativeWebView to determine if it’s running in a supported mobile WebView. If this handler doesn’t exist with this exact name, the checkout UI will not render properly.

1. Define API Models
// Response model
struct CheckoutLinkResponse: Codable {
let link: String
}
// Request models
struct CheckoutRequest: Codable {
struct Subtotal: Codable {
let currency: String
let cents: Int
}
struct ChargebackProtectionData: Codable {
let productType: String
let productName: String
let quantity: Int
}
let subtotal: Amount
let chargebackProtectionData: [ChargebackProtectionData]
// ...
// NOTE: You may need more fields than this basic example.
}
2. Handle API Calls
class WebViewModel: ObservableObject {
@Published var checkoutURL: URL?
@Published var isLoading = false
@Published var errorMessage: String?
@Published var transactionStatus: String?
func fetchCheckoutURL() async {
await MainActor.run {
isLoading = true
errorMessage = nil
}
do {
guard let url = URL(string: "https://api-sandbox.coinflow.cash/api/checkout/link") else {
throw URLError(.badURL)
}
let requestBody = CheckoutRequest(
subtotal: CheckoutRequest.Amount(currency: "USD", cents: 100),
chargebackProtectionData: [
CheckoutRequest.Product(
productType: "dataStorage",
productName: "test",
quantity: 1
)
]
)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "accept")
request.addValue("YOUR_AUTHORIZATION_KEY", forHTTPHeaderField: "Authorization")
request.addValue("YOUR_USER_ID", forHTTPHeaderField: "x-coinflow-auth-user-id")
request.httpBody = try JSONEncoder().encode(requestBody)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
throw URLError(.badServerResponse)
}
let checkoutResponse = try JSONDecoder().decode(CheckoutLinkResponse.self, from: data)
await MainActor.run {
if let url = URL(string: checkoutResponse.link) {
self.checkoutURL = url
} else {
self.errorMessage = "Invalid URL in response"
}
self.isLoading = false
}
} catch {
await MainActor.run {
self.errorMessage = "API Error: \(error.localizedDescription)"
self.isLoading = false
}
}
}
func handleWebMessage(_ message: String) {
print("Received message from web: \(message)")
switch message {
case "success":
transactionStatus = "Success"
case "authDeclined":
transactionStatus = "Failed"
default:
break
}
}
}
3. Create a WebView
struct WebViewRepresentable: UIViewRepresentable {
@ObservedObject var viewModel: WebViewModel
func makeUIView(context: Context) -> WKWebView {
let configuration = WKWebViewConfiguration()
let userContentController = WKUserContentController()
userContentController.add(context.coordinator, name: "ReactNativeWebView") // Very important. The name must be "ReactNativeWebView"
configuration.userContentController = userContentController
return WKWebView(frame: .zero, configuration: configuration)
}
func updateUIView(_ webView: WKWebView, context: Context) {
if let checkoutURL = viewModel.checkoutURL,
webView.url == nil || webView.url?.absoluteString != checkoutURL.absoluteString {
webView.load(URLRequest(url: checkoutURL))
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, WKScriptMessageHandler {
var parent: WebViewRepresentable
init(_ parent: WebViewRepresentable) {
self.parent = parent
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard let messageString = message.body as? String else { return }
DispatchQueue.main.async {
self.parent.viewModel.handleWebMessage(messageString)
}
}
}
}
4. Show Webview
struct ContentView: View {
@StateObject private var viewModel = WebViewModel()
var body: some View {
VStack {
if viewModel.isLoading {
ProgressView("Loading checkout...")
} else if let errorMessage = viewModel.errorMessage {
Text("Error: \(errorMessage)")
.foregroundColor(.red)
.padding()
Button("Retry") {
Task {
await viewModel.fetchCheckoutURL()
}
}
.padding()
} else {
WebViewRepresentable(viewModel: viewModel)
.edgesIgnoringSafeArea(.all)
}
}
.onAppear {
Task {
await viewModel.fetchCheckoutURL()
}
}
}
}
5. Handle Result
// Add this to your ContentView
if let status = viewModel.transactionStatus {
Text("Transaction status: \(status)")
.padding()
.background(status == "Success" ? Color.green.opacity(0.2) : Color.red.opacity(0.2))
.cornerRadius(8)
}
Response Example
{"success":true}

Define API Models for Request and Response

Create models matching Coinflow’s API structure

Fetch a Checkout Link

Implement a ViewModel that fetches the checkout URL.

Create a WebView Representable

Implement a WebView that loads the Coinflow checkout URL and listens for messages.

Update ContentView to Show Loading State and WebView

Connect everything in your ContentView.

Handle Transaction Results

You can update the UI based on transaction status