- 웹뷰 선언
// 웹뷰 선언
private var webView: WKWebView!
...
override func viewDidLoad() {
super.viewDidLoad()
viewConfigure()
...
}
func viewConfigure() {
// WebView
let webConfiguration = WKWebViewConfiguration()
let contentController = WKUserContentController()
//웹 컨텍스트와 연결할 사용자 content 컨트롤러를 추가 -> "scriptHandler" 의 이름으로 주고받음
contentController.add(self, name: "scriptHandler")
webConfiguration.userContentController = contentController
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
let preferences = WKWebpagePreferences()
preferences.allowsContentJavaScript = true
webView.configuration.defaultWebpagePreferences = preferences
view.addSubview(webView)
}
- 웹뷰 로드
override func viewDidLoad() {
super.viewDidLoad()
...
DispatchQueue.main.async {
loadURL()
}
}
// 웹뷰 로드
private func loadURL() {
// 네트워크 체크
.....
// 로드할 url 세팅
let urlString = "https://www.naver.com/"
var urlRequest = URLRequest(url: URL(string: urlString)!)
urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
urlRequest.httpMethod = "POST"
let paramBody = "\(Params.LANGUAGE)=\(languageCode)"
urlRequest.httpBody = paramBody.data(using: .utf8)
// 웹뷰 내 url 로드
webView.load(urlRequest)
}
- 웹뷰 통신 로딩
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 웹뷰 로딩시 로딩 indicator 뷰를 보여주기 위한 로딩 감지 옵저버 등록
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.isLoading), options: .new, context: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// 로딩 감지 옵저버 해제
webView.removeObserver(self, forKeyPath: #keyPath(WKWebView.isLoading))
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "loading" {
if webView.isLoading {
// 로딩바 나타내기
.....
} else {
// 로딩바 없애기
.....
}
}
}
- UIDelegate
/* extension for WKUIDelegate */
extension ExampleViewController: WKUIDelegate {
// 웹뷰 내에서 윈도우 팝업 창을 열 경우 (window.open)
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
guard let _ = navigationAction.request.url else { return nil }
if navigationAction.targetFrame == nil {
webView.load(navigationAction.request)
}
return nil
}
}
- 브라우저에서 팝업으로 열리는 창에 대하여 처리해주는 delegate 함수임. (window.open를 위한 delegate)
- 위 코드는 윈도우 팝업 창을 모바일 앱에서는 화면전환으로 load 해주는 방법으로 채택하고 있음.
- Massage Handler
/* extension for WKScriptMessageHandler */
extension ExampleViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
switch message.name {
// 위 웹뷰 세팅 때 key값 name을 매칭 ("scriptHandler")
case "scriptHandler":
guard
let bodyStr = message.body as? String,
let json = bodyStr.data(using: .utf8)
else {
// 데이터 처리 도중 오류 발생 알림
.....
return
}
do {
guard
let authentificationData = try JSONSerialization.jsonObject(with: json, options:[]) as? NSDictionary
else {
// 데이터 처리 도중 오류가 발생 알림
return
}
// 웹단에서 받은 파싱된 데이터
print(authentificationData)
} catch let error {
// 데이터 파싱 오류 알림
.....
}
default:
break
}
}
}
- 위의 contentController.add(self, name: "scriptHandler") 에서 설정한 name key를 받아서 데이터 수신
'Swift' 카테고리의 다른 글
[Swift] WebKit 의 웹 관련 캐시 삭제 하는 방법 (0) | 2022.12.16 |
---|---|
[Swift] Alamofire 통신에서 캐시 사용 안하는 방법 (0) | 2022.11.25 |
[Swift] UIScrollView 내 UITextView 의 Cursor 로 focus scroll 하는 방법 (0) | 2022.11.17 |
[Swift] ScrollView 에서 Button Highlight Delay가 생길 때 (2) | 2022.11.11 |
[Swift] CLLocationManager.locationServicesEnabled() Issue 문제 (2) | 2022.11.02 |