How to use LiveActivity in kotlin multiplatform ios project

I want to use LiveActivity function in my kotlin multiplatform ios project.But i cant find any kotlin Api.Is there any other way to use LiveActivity?
i tried cinterpo.but it seems i did not get the right way.can anybody tell me the right way?
Answer
Currently, there is no official Kotlin Multiplatform (KMP) API or library that directly supports Live Activities. But you can still use Live Activities in a KMP project, by leveraging platform-specific code using Kotlin's expect/actual mechanism or calling native iOS code directly via interop with Swift/Objective-C.
Write Native iOS Code (Swift)
You’ll need to implement the Live Activity functionality in Swift using ActivityKit.
Expose Swift Code to KMP via Objective-C
- Mark the class with
@objc
and inherit fromNSObject
- Ensure it's visible in the generated
*.framework
headers
It will look something like this:
- Mark the class with
@objc class LiveActivityBridge: NSObject {
@objc static func startLiveActivity(withTitle title: String) {
if #available(iOS 16.1, *) {
LiveActivityManager.shared.startActivity(title: title)
}
}
@objc static func updateLiveActivityProgress(_ progress: Double) {
if #available(iOS 16.1, *) {
LiveActivityManager.shared.updateProgress(to: progress)
}
}
@objc static func stopLiveActivity() {
if #available(iOS 16.1, *) {
LiveActivityManager.shared.endActivity()
}
}
}
- Call from Kotlin Multiplatform
import platform.Foundation.NSObject
actual class LiveActivityController {
actual fun start(title: String) {
LiveActivityBridge.startLiveActivityWithTitle(title)
}
actual fun updateProgress(progress: Double) {
LiveActivityBridge.updateLiveActivityProgress(progress)
}
actual fun stop() {
LiveActivityBridge.stopLiveActivity()
}
}
Define an expect
class in the common module if you want to call it from shared code:
expect class LiveActivityController {
fun start(title: String)
fun updateProgress(progress: Double)
fun stop()
}
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles