Search code examples
androidkotlincoil

Get loaded picture URL from Coil


I have a question about getting the loaded picture URL from Coil. The reason why is because I'm using https://unsplash.it/200/200 to get a random image URL which will become something like Image URL, so how can I get the second URL when the image is loaded if I pass the first one to Coil? Here is the code I'm using:

SubcomposeAsyncImage(
                modifier = Modifier
                    .width(imageWidth)
                    .height(imageHeight)
                    .align(Alignment.BottomCenter)
                    .clip(CircleShape),
                model = ImageRequest.Builder(LocalContext.current)
                    .data("https://unsplash.it/200/200")
                    .crossfade(true)
                    .build(),
                alignment = Alignment.BottomCenter,
                contentDescription = "Avatar Image"
            ) {
                val state = painter.state
                if (state is AsyncImagePainter.State.Loading) {
                    Box(
                        modifier = Modifier.size(10.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator(strokeWidth = 2.dp, color = BlueColor)
                    }
                } else {
                    SubcomposeAsyncImageContent(
                        modifier = Modifier.clip(CircleShape),
                        contentScale = ContentScale.Fit
                    )
                }
            }

Solution

  • Here is the solution I found. The trick is to use OkHttp to get the desired link since the first link returns a 302 status code (It will redirect to another link).

    Here is the code:

    fun randomAvatarUrl() {
    val client = OkHttpClient.Builder()
        .followRedirects(false)
        .build()
    val request = Request.Builder()
        .url(avatarUrl)
        .build()
    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            e.printStackTrace()
        }
    
        override fun onResponse(call: Call, response: Response) {
            val originalURL = response.headers["Location"]
            if (originalURL != null) {
                Log.d("Tag", originalURL)
            }
        }
    })}
    

    Then pass originalURL to Coil and store it.