Skip to content

Commit

Permalink
Encode special characters in URL when downloading image on iOS
Browse files Browse the repository at this point in the history
  • Loading branch information
msasikanth committed Sep 23, 2023
1 parent 8256999 commit 03a5ba7
Showing 1 changed file with 12 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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<ImageLoaderState> {
Expand Down Expand Up @@ -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

Expand Down

0 comments on commit 03a5ba7

Please sign in to comment.