Hi,
currently, as i do not found how to implement it in Kotlin, i've a a swift framework included as a library.
this framework just do conversion from NSData to String and... String to NSData like this:
String(data: data, encoding: .utf8)
str.data(using: .utf8)
i would like to implement it directly with Kotlin, how can i achieve that?
@SBNTT
Have you tried using Objective-C variants of the same methods through Objective-C interop?
(str as NSString).dataUsingEncoding(NSUTF8StringEncoding)!!
NSString.create(data, NSUTF8StringEncoding) as String
Excellent,
thanks @SvyatoslavScherbina !
There is a shorthand to make it more confortable to use
@Suppress("CAST_NEVER_SUCCEEDS")
fun String.nsdata(): NSData? {
return (this as NSString).dataUsingEncoding(NSUTF8StringEncoding)
}
fun NSData.string(): String? {
return NSString.create(this, NSUTF8StringEncoding) as String?
}
and use it like this:
val data: NSData? = "fsdfsdfsfsdf".nsdata()
val str: String? = data.string()
No need to suppress class cast:
fun String.nsdata(): NSData? =
NSString.create(string = this).dataUsingEncoding(NSUTF8StringEncoding)
fun NSData.string(): String? =
NSString.create(data = this, encoding = NSUTF8StringEncoding)?.toString()
Most helpful comment
@SBNTT
Have you tried using Objective-C variants of the same methods through Objective-C interop?