How to use Base64 in Multiplatform (iOS/Android)

I am new to the KMM world, coming from Android background.
While I could easily modulize my code and use the kmm for my business logic in a common module, there are still some small things that do not work as nicely as expected.

Today after trying to build the common module for iOS, it seems like I was using Android’s base64 decoder in my common code.

The easiest thing which popped into my mind was to use the expect and actual. Then it worked fine for Android, but it was not possible to make the actual method for iOS to decode a simple base64 string.

I was wondering if there are any workarounds to decode Base64 in a common module.

1 Like

Ktor has base 64. If you don’t need the whole of ktor you can just use the ktor-utils library: https://mvnrepository.com/artifact/io.ktor/ktor-utils?repo=kotlin-ktor

1 Like

I also faced a similar issue when migrated my project to use Kotlin Multiplatform.

Currently my project uses Ktor (instead of Retrofit) and everything works fine. But the Base64 decode is still a huge problem.

@dalewking:
The Ktor Base64 decoder seems to be an internal Ktor API which I could not use in my KMM project.
It is also marked as deprecated(?) in the docs: https://api.ktor.io/1.4.1/io.ktor.util/decode-base64.html
It would be amazing if I could find a workaround to use it.

Sorry, guess that’s what I get for replying from my phone

1 Like

No worries! :slight_smile:
Only surprised to know that using such a simple function is so complicated! haha :laughing:

I have the same problem and in the end, I wrote it by myself, but I would love to see it in the std lib.
BTW the ktor APIs are just renamed, but are still included.

1 Like

I’ve written my own Kotlin multiplatform Base64 implementation. It doesn’t require any extra dependencies. I’ve used java.util.Base64 as base and ripped out all the platform specific and imho unnecessary parts.
The code is at Kotlin Multiplatform Base64 - no extra dependencies. Based on Java's implementation. · GitHub

There is also a JVM test to verify it against Java’s implementation.

1 Like

I have also found this library GitHub - 05nelsonm/component-encoding: Base16/32/64 encoding for Kotlin Multiplatform