From 40c452ce619dab7aa52e2d43bf04521a0aaa9c33 Mon Sep 17 00:00:00 2001 From: Vaibhav Jaiswal Date: Tue, 8 Jul 2025 13:11:06 +0530 Subject: [PATCH] fix: App Crash on Invalid URL --- .../multiplatform/webview/web/IOSWebView.kt | 41 +++++++++++-------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/webview/src/iosMain/kotlin/com/multiplatform/webview/web/IOSWebView.kt b/webview/src/iosMain/kotlin/com/multiplatform/webview/web/IOSWebView.kt index 85db87ba..bb04a87c 100644 --- a/webview/src/iosMain/kotlin/com/multiplatform/webview/web/IOSWebView.kt +++ b/webview/src/iosMain/kotlin/com/multiplatform/webview/web/IOSWebView.kt @@ -10,6 +10,7 @@ import kotlinx.cinterop.allocArrayOf import kotlinx.cinterop.memScoped import kotlinx.cinterop.useContents import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch import platform.Foundation.HTTPBody import platform.Foundation.HTTPMethod import platform.Foundation.NSBundle @@ -50,20 +51,28 @@ class IOSWebView( url: String, additionalHttpHeaders: Map, ) { - val request = - NSMutableURLRequest.requestWithURL( - URL = NSURL(string = url), - ) - additionalHttpHeaders.all { (key, value) -> - request.setValue( - value = value, - forHTTPHeaderField = key, - ) - true + try { + val request = NSMutableURLRequest.requestWithURL(URL = NSURL(string = url)) + additionalHttpHeaders.forEach { (key, value) -> + request.setValue(value = value, forHTTPHeaderField = key) + } + webView.loadRequest(request = request) + } catch (e: Exception) { + KLogger.e { "The url is not a valid web URL: $url" } + scope.launch { + val errorHtml = + """ + + Error + +

Error Loading URL

+

Could not load: $url

+

Error: ${e.message}

+ + """.trimIndent() + loadHtml(errorHtml) + } } - webView.loadRequest( - request = request, - ) } override suspend fun loadHtml( @@ -97,7 +106,7 @@ class IOSWebView( WebViewFileReadType.ASSET_RESOURCES -> { val resourcePath = (NSBundle.mainBundle.resourcePath ?: "") + - "/compose-resources/assets/" + fileName + "/compose-resources/assets/" + fileName fileURL = NSURL.fileURLWithPath(resourcePath) val parentDir = (resourcePath as NSString).stringByDeletingLastPathComponent() @@ -131,11 +140,11 @@ class IOSWebView( if (finalReadAccessURL.path.isNullOrEmpty()) { KLogger.e { "Critical: finalReadAccessURL is null or has an empty path. " + - "Cannot load file with proper read access for ${fileURL.absoluteString}" + "Cannot load file with proper read access for ${fileURL.absoluteString}" } loadHtml( "Error: Cannot determine read access URL " + - "for ${fileURL.absoluteString}", + "for ${fileURL.absoluteString}", ) return }