Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
34 changes: 34 additions & 0 deletions P2PShopping/P2PShopping/Bridge/LocationBridgeHandler.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import Foundation
import WebKit

/// Issue #27 - [Bridge] Expose requestLocationPermission() to JS (iOS)
class LocationBridgeHandler: NSObject, WKScriptMessageHandler {

private let permissionManager: LocationPermissionManager

init(permissionManager: LocationPermissionManager) {
self.permissionManager = permissionManager
}

/// Called when JS calls: window.webkit.messageHandlers.locationBridge.postMessage("requestLocationPermission")
func userContentController(
_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage
) {
guard message.name == "locationBridge",
let action = message.body as? String,
action == "requestLocationPermission" else { return }

Task { @MainActor in
self.permissionManager.requestWhenInUsePermission()

// Wait for the permission result then send it back to JS
try? await Task.sleep(nanoseconds: 1_000_000_000)

let result = self.permissionManager.permissionGranted ? "Granted" : "Denied"

let js = "window.onLocationPermissionResult('\(result)')"
message.webView?.evaluateJavaScript(js, completionHandler: nil)
}
}
}
2 changes: 1 addition & 1 deletion P2PShopping/P2PShopping/ContentView.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import SwiftUI

struct ContentView: View {
@StateObject private var locationManager = LocationPermissionManager()
@EnvironmentObject private var locationManager: LocationPermissionManager

var body: some View {
VStack(spacing: 24) {
Expand Down
14 changes: 14 additions & 0 deletions P2PShopping/P2PShopping/P2PShoppingApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,26 @@
//

import SwiftUI
import WebKit

@main
struct P2PShoppingApp: App {

@StateObject private var locationManager = LocationPermissionManager()

var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(locationManager)
.onAppear {
setupBridge()
}
}
}

private func setupBridge() {
let contentController = WKUserContentController()
let bridgeHandler = LocationBridgeHandler(permissionManager: locationManager)
contentController.add(bridgeHandler, name: "locationBridge")
}
}