https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
n

Nikolai

04/11/2019, 10:03 AM
Hi, eveyone Is where any multiplatform Base64 library? Or maybe where is a way to convert string to NSString? I need to encode string with base64 in actual class for iOS platform
o

olonho

04/11/2019, 10:20 AM
Feel free to create .def file with https://github.com/JetBrains/kotlin-native/blob/master/common/src/hash/cpp/Base64.cpp which encodes/decodes string to base64.
s

svyatoslav.scherbina

04/11/2019, 10:49 AM
Or maybe where is a way to convert string to NSString?
Sure.
str as NSString
.
n

Nikolai

04/11/2019, 10:54 AM
@svyatoslav.scherbina , thanks but for me compiler say “this cast can never success”.
@olonho Thanks
s

svyatoslav.scherbina

04/11/2019, 11:05 AM
@Nikolai just ignore this warning.
n

Nikolai

04/11/2019, 11:08 AM
@svyatoslav.scherbina Ok, thanks I will try
l

louiscad

04/11/2019, 11:42 AM
@svyatoslav.scherbina about that warning, is there an existing issue we can follow to remove it in that special case? I'd rather not take the habit to ignore warnings.
j

Jurriaan Mous

04/11/2019, 11:57 AM
My version of iOS Base64 encoder (I work without padding so I remove it)
Copy code
/** Object to convert base 64 */
actual object Base64 {
    /** Decode [base64] string into bytes array */
    actual fun decode(base64: String): ByteArray {
        // For this library end padding is mandatory so add possible missing padding
        val value = base64.padEnd(
            length = ((base64.length + 3) / 4) * 4,
            padChar = '='
        )

        val data = NSData.create(value, 0) ?: throw ParseException("Invalid Base64 value $base64")
        @Suppress("UNCHECKED_CAST")
        val bytePtr = (data.bytes as CPointer<uint8_tVar>)

        return ByteArray(data.length.toInt()) { index ->
            bytePtr[index].toByte()
        }
    }

    /** Encode [bytes] array into a base64 String */
    actual fun encode(bytes: ByteArray) = memScoped {
        NSData.create(
            bytesNoCopy = bytes.toCValues().getPointer(this),
            length = bytes.size.toULong()
        ).base64EncodedStringWithOptions(0).dropLastWhile {
            // Remove any Base64 padding
            it == '='
        }
    }
}
s

svyatoslav.scherbina

04/11/2019, 12:49 PM
@louiscad feel free to create one. Alternatively one can use
NSString.create(string = str)
.
l

louiscad

04/11/2019, 1:06 PM
r

Ran

02/02/2021, 8:27 AM
@svyatoslav.scherbina Cannot use
NSString.create(string = str)
in K/N 1.4.10
s

svyatoslav.scherbina

02/02/2021, 8:33 AM
Cannot use 
NSString.create(string = str)
 in K/N 1.4.10
According to your screenshot, you don’t use the named argument (
string =
), which is important here.
NSString.create(string = str)
totally works for me.
r

Ran

02/02/2021, 8:34 AM
Get it, thanks.
7 Views