https://kotlinlang.org logo
n

Nicolas Verinaud

07/01/2021, 1:46 PM
[SOLVED] Hi ! I try to convert an ObjC method which uses C functions in Kotlin Native but it does not work 😞 Here is the ObjC / C code :
Copy code
- (NSString *) getSysInfoByName:(char *)typeSpecifier
{
    size_t size;
    sysctlbyname(typeSpecifier, NULL, &size, NULL, 0);
    
    char *answer = malloc(size);
    sysctlbyname(typeSpecifier, answer, &size, NULL, 0);
    
    NSString *results = [NSString stringWithCString:answer encoding: NSUTF8StringEncoding];

    free(answer);
    return results;
}
And my Kotlin version :
Copy code
private fun sysInfoByName(identifier: String): String? {
        val size = cValue<size_tVar>()
        sysctlbyname(identifier, null, size, null, 0)

        var result: String? = ""

        memScoped {
            val value = allocArray<charfVar>(size.size)
            sysctlbyname(identifier, value, size, null, 0)

            result = NSString.stringWithCString(cString = value, NSUTF8StringEncoding)
        }

        return result
    }
The result is always empty. 😞 Do you know why ? 😇
Or if you are aware of any libraries capable of providing the precise model name on iOS (ex: iPhone5,2)
b

borisdamato

07/01/2021, 3:57 PM
This should work:
Copy code
val deviceModel = memScoped {
        val sysInfo = alloc<utsname>()
        if (uname(sysInfo.ptr) == 0) {
            sysInfo.machine.toKString()
        } else {
            "Unknown"
        }
    }
(for simulators it will return x86_64, but will return iPhone11,8 etc for real devices)
l

louiscad

07/01/2021, 9:13 PM
@Nicolas Verinaud There's a much higher level API to do this in UIKit: look at
UIDevice.currentDevice
n

Nicolas Verinaud

07/02/2021, 4:11 AM
@borisdamato yep it works, thank you ! 👍
@louiscad I looked at
UIDevice
but it only returns “iPhone” or “iPad” or “iPod” xD
Which is not super useful when trying to provide support to a customer.
l

louiscad

07/02/2021, 5:03 AM
I'm pretty sure there's one of the members of they API that returns the device model @Nicolas Verinaud
I'll check when I'm back on the computer
11 Views