예전부터 WKWebView에 대해서는 관심을 가지고 있었는데, 잘(?) 다루는 방법에 대해서 자료가 좀 적기도하고 네이티브에서는 궂이? 잘쓰려고 하지않기에 등한시 했던 부분이 있습니다
하지만 카카오같은 곳에서 세션을 발표할때 웹뷰의 비동기 동작이나 통신을 어떻게 하는지 꿀팁을 소개해 주셔서 능력이 닿는한 파해쳐 보려고 합니다
https://tech.kakaopay.com/post/ifkakao2022-ios-webview/
### Script
- Native에서 web에게 일방적으로 정보를 보낼 때 사용
- Event(라이프 사이클 등 ) 또는 Button Action과 같이 간단한 정보를 전송
### JSAPI(JavaScript API)
- Web에서 Native 로직이 필요한 모든 경우에 사용
- Web에서 정보를 받은 후, Native의 결과 값 전달
- 정보는 *postMessage() 로 전송하게 됩니다*
- command, parameter를 통해 Web에서 Native에게 전달하고자하는 값을 전달 받습니다
- extra: id 값으로 동일한 commandd의 비동기 처리를 구분하고, 디버깅도 id에 따라온 값을 보고 처리할수 있습니다. 이 id는 JSapi별로 다른 id값을 갖습니다
- 이 예시는 open이라는 commnad값을 받고 파라미터로 url을 받아 여는 함수입니다
### Configuration
- Native처럼 사용자에게 이질감 없는 interaction, UI를 제공하기 위해 웹뷰를 구성할 때 사전에 약속된 값으로 UI핸들링
- 타이밍상 Native에서 더 자연스러운 기능은 Native에서 구현하고 Configuration으로 구분
- 웹뷰 UI 설정 값을 Configuration으로 받아 WebViewController객체 생성
###Transparent
---
### 실제 서비스에서 호출되는 형태
1. 웹뷰 컨트롤러 생성
2. 이벤트 처리
- 이미 핸들되었는지 체크하고 이값이 `false` 일때 처리를 시작합니다
- 처리를 체크하는 함수는 아래와 같습니다
### 헤더세팅방법
private var headers: [String: String] {
let bundleVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
var header = ["Content-Type": "application/json"]
header["app-device-uuid"] = UUID().uuidString
header["app-device-os-version"] = UIDevice.current.systemVersion
header["app-device-device-manufacturer"] = "apple"
header["app-version"] = bundleVersion
return header
}
let url = Bundle.main.url(forResource: "index", withExtension: "html")!
var urlRequest = URLRequest(url: url)
headers.forEach { urlRequest.setValue($0.value, forHTTPHeaderField: $0.key) }
// webView.loadFileURL(url, allowingReadAccessTo: url)
webview.load(urlRequest)
참고
[[iOS] WKWebView 정리 Swift](https://thoonk.tistory.com/87) [https://github.com/Lision/WKWebViewJavascriptBridge](https://github.com/Lision/WKWebViewJavascriptBridge) [https://github.com/bernikovich/WebViewWarmUper](https://github.com/bernikovich/WebViewWarmUper)
[[iOS - swift] 1. WKWebView 개념 (UIWebView, AJAX, XHR, 캐시, 쿠키)](https://ios-development.tistory.com/700)
[[iOS - swift] 2. WKWebView 사용 방법 (웹뷰, 쿠키, WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate)](https://ios-development.tistory.com/701)
[[iOS - swift] RxWebKit, WKWebView, messageHandler 사용 방법 웹뷰 통신(native <-> javascript), 콜백](https://ios-development.tistory.com/942)
[[iOS - swift] 2. WKWebView - Header 설정, Cookie 설정, access token 전달, deeplink 수신 방법](https://ios-development.tistory.com/751)
[iOS WKWebView Communication Using Javascript and Swift](https://medium.com/john-lewis-software-engineering/ios-wkwebview-communication-using-javascript-and-swift-ee077e0127eb)
[How does the iOS 14 API WKScriptMessageHandlerWithReply work for communicating with JavaScript from iOS?](https://stackoverflow.com/questions/65270083/how-does-the-ios-14-api-wkscriptmessagehandlerwithreply-work-for-communicating-w)