[KMP] IOS에서 ObserverProtocol이용하기

WonDDak·2024년 11월 1일
0

KMP- Kotlin MultiPlatform

목록 보기
11/12

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;
  1. build.gradle.kts에 다음을 입력
    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")
            }
        }
    }
  1. 사용 예시
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())
            }
        }
    }
}
profile
안녕하세요. 원딱입니다.

0개의 댓글