KMP/CMP에서 ObserverProtocol이용하는 법
1.src/nativeInterop/cinterop
에 다음 파일을 저장 observer.def
language = Objective-C
---
#import <Foundation/Foundation.h>
@protocol Observer
@required
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSKeyValueChangeKey, id> *)change
context:(void *)context;
@end;
listOf(
iosX64(),
iosArm64(),
iosSimulatorArm64()
).forEach {
val path = projectDir.resolve("src/nativeInterop/cinterop/observer")
it.binaries {
all {
linkerOpts("-F $path")
linkerOpts("-ObjC")
}
framework {
baseName = "myModule"
isStatic = true
}
}
it.compilations.getByName("main") {
cinterops.create("observer") {
compilerOpts("-F $path")
}
}
}
import kotlinx.cinterop.COpaquePointer
import kotlinx.cinterop.ExperimentalForeignApi
import observer.ObserverProtocol
import platform.Foundation.NSNumber
import platform.darwin.NSObject
import kotlin.math.roundToInt
internal const val PROGRESS_KEY = "estimatedProgress"
@ExperimentalForeignApi
class WKWebViewObserver(
private val webViewPageStateListener: WebViewPageStateListener?
) :
NSObject(),
ObserverProtocol {
override fun observeValueForKeyPath(
keyPath: String?,
ofObject: Any?,
change: Map<Any?, *>?,
context: COpaquePointer?,
) {
if (keyPath == PROGRESS_KEY) {
val progress = change?.get("new") as? NSNumber
if (progress != null) {
webViewPageStateListener?.onProgress(null,(progress.floatValue * 100).roundToInt())
}
}
}
}