Hi, why is this code not working. ```LaunchedEffec...
# multiplatform
m
Hi, why is this code not working.
Copy code
LaunchedEffect(Unit) {
        if (!CHHapticEngine.capabilitiesForHardware().supportsHaptics) return@LaunchedEffect

        val hapticEngine = CHHapticEngine() // Nullpointer exception here.
        val hapticDict = mapOf(
            CHHapticPatternKeyPattern to listOf(
                mapOf(
                    CHHapticPatternKeyEvent to listOf(
                        mapOf(
                            CHHapticPatternKeyEventType to CHHapticEventTypeHapticTransient,
                            CHHapticPatternKeyTime to CHHapticTimeImmediate,
                            CHHapticPatternKeyEventDuration to 1.0
                        )
                    )
                )
            )
        )
        val pattern = CHHapticPattern(dictionary = hapticDict as Map<Any?, *>, error = null)
        val player = hapticEngine.createPlayerWithPattern(pattern = pattern, error = null)
        player?.startAtTime(0.0, error = null)
    }
A better question might be, how can i use haptic engine in iOS
a
Hi there. There is multiplatform implementation of haptics:
Copy code
val haptic = LocalHapticFeedback.current
Row(
    Modifier.clickable {
        haptic.performHapticFeedback(HapticFeedbackType.LongPress)
    }
)
m
Hi, thank you. I am looking to implement a more platform specific haptic feedback library. I can initialize the CHHapticPattern in swift but not in kotlin.
a
Ah, sorry, missed a line with
// Nullpointer exception here.
. let me check.
It seems like constructor with no params is not available for the
CHHapticsEngine
. Try the following code:
Copy code
memScoped {
                val result = alloc<ObjCObjectVar<NSError?>>()
                val hapticEngine = CHHapticEngine(andReturnError = result.ptr)
                val error = result.value

                if (error == null) {
                    println(">>>>> Okay")
                } else {
                    println(">>>>> Not okay: $error")
                }
            }
I don't have ready-to-test device to verify the code.
m
Untitled.kt
Thanks alot, i replaced my code with your code and it worked to the point where i initialized my CHHapticPattern CHHapticPattern: 0x2822f5900 >>>>> Okay Haptic Dict: {Pattern={EventType=HapticTransient, Time=0.0, EventDuration=0.1}} 2024-06-16 153007.254246+0200 Rattlesnake[940:121420] -[__NSCFConstantString enumerateKeysAndObjectsUsingBlock] unrecognized selector sent to instance 0x229c60408 Uncaught Kotlin exception: kotlin.NullPointerException
For anyone else encountering this. Here is my solution to a working engine.
👍 1
a
Overall tip for those who writes native code in Kotlin: it's much more convenient to transfer code from Obj-C, rather then from Swift, because Native to Kotlin interop is based on Obj-C API.
m
I saw somewhere that there are plans to make it build to swift instead of objective-c