From 03a5ba704db0c620c127603e6dd1c0e56c429ffb Mon Sep 17 00:00:00 2001 From: Sasikanth Miriyampalli Date: Sat, 23 Sep 2023 09:13:16 +0530 Subject: [PATCH] Encode special characters in URL when downloading image on iOS --- .../rss/reader/components/IOSImageLoader.kt | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/shared/src/iosMain/kotlin/dev/sasikanth/rss/reader/components/IOSImageLoader.kt b/shared/src/iosMain/kotlin/dev/sasikanth/rss/reader/components/IOSImageLoader.kt index 88f0ceb93..dc98405e8 100644 --- a/shared/src/iosMain/kotlin/dev/sasikanth/rss/reader/components/IOSImageLoader.kt +++ b/shared/src/iosMain/kotlin/dev/sasikanth/rss/reader/components/IOSImageLoader.kt @@ -48,12 +48,16 @@ import org.jetbrains.skia.ImageInfo import org.jetbrains.skia.Rect import org.jetbrains.skia.SamplingMode import platform.Foundation.NSCachedURLResponse +import platform.Foundation.NSCharacterSet import platform.Foundation.NSData import platform.Foundation.NSHTTPURLResponse +import platform.Foundation.NSString import platform.Foundation.NSURL import platform.Foundation.NSURLCache import platform.Foundation.NSURLRequest +import platform.Foundation.URLFragmentAllowedCharacterSet import platform.Foundation.create +import platform.Foundation.stringByAddingPercentEncodingWithAllowedCharacters @Composable internal fun rememberImageLoaderState(url: String?): State { @@ -112,25 +116,26 @@ class IOSImageLoader : ImageLoader { diskPath = "dev_sasikanth_rss_reader_images_cache" ) + @Suppress("CAST_NEVER_SUCCEEDS") override suspend fun getImage(url: String, size: Int?): ImageBitmap? { return withContext(Dispatchers.IO) { - val cachedImage = loadCachedImage(url) + val encodedUrl = + (url as NSString).stringByAddingPercentEncodingWithAllowedCharacters( + NSCharacterSet.URLFragmentAllowedCharacterSet + ) + ?: return@withContext null + val cachedImage = loadCachedImage(encodedUrl) val data = if (cachedImage != null) { cachedImage } else { - downloadImage(url) ?: return@withContext null + downloadImage(encodedUrl) ?: return@withContext null } return@withContext Image.makeFromEncoded(data).toBitmap(size).asComposeImageBitmap() } } - private fun hasImageCache(url: String): Boolean { - val request = createNSURLRequest(url) ?: return false - return urlCache.cachedResponseForRequest(request) != null - } - private fun loadCachedImage(url: String): ByteArray? { val request = createNSURLRequest(url) ?: return null