[지난 포스팅]
[참고자료]
넘 잘 나와있다.
참고자료를 바탕으로 요기 로그인해서 자바스크립트 키를 받아서 index.html에 넣어줘야함
지난번 카카오 주소받기의 index.html과 같고,
고쳐진 부분은 키 값 추가, execDaumPostcode() 부분을 고쳐줌
Index.html
<!DOCTYPE html>
<html lang="ko">
<head>
...
</head>
<body onload="execDaumPostcode()">
...
<script src="https://spi.maps.daum.net/imap/map_js_init/postcode.v2.js"></script>
<script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey={***자바스크립트 키 넣는부분***}&libraries=services"></script>
<script>
window.addEventListener("message", onReceivedPostMessage, false);
function onReceivedPostMessage(event) {
...
}
function onReceivedActivityMessageViaJavascriptInterface(json) {
//..ex deconstruct data into action & params
var data = JSON.parse(json);
var action = data.action;
var params = data.params;
console.log("onReceivedActivityMessageViaJavascriptInterface " + event);
}
function postMessageToiOS(postData) {
window.webkit.messageHandlers.callBackHandler.postMessage(postData);
}
var geocoder = new kakao.maps.services.Geocoder();
var element_layer = document.getElementById("layer");
function execDaumPostcode() {
new daum.Postcode({
oncomplete: function (data) {
var jibunAddress = "";
if (data.jibunAddress == "") {
jibunAddress = data.autoJibunAddress;
} else if (data.autoJibunAddress == "") {
jibunAddress = data.jibunAddress;
}
geocoder.addressSearch(data.roadAddress, (result, status) => {
if (status === kakao.maps.services.Status.OK) {
x = result[0].y // 위도
y = result[0].x // 경도
var postData = {
roadAddress: data.roadAddress,
jibunAddress: jibunAddress,
zonecode: data.zonecode,
x: x,
y: y
};
window.postMessageToiOS(postData);
}
});
},
width: "100%",
height: "100%",
}).embed(element_layer);
element_layer.style.display = "block";
initLayerPosition();
}
...
</script>
</body>
</html>
https://postcode.map.daum.net/guide
다른 데이터들이 필요하다면 홈페이지에서 확인!
본인은 웹시트 바인딩 변수, 주소, 위도, 경도 총 4개를 받아와야 했기 때문에 아래와 같이 전달해 주었다.
SwiftUI 코드
struct WebView: UIViewRepresentable {
let request: URLRequest
private var webView: WKWebView?
@Binding var showingWebSheet: Bool
@Binding var location: String
@Binding var latitude: String
@Binding var longitude: String
init(request: URLRequest, showingWebSheet: Binding<Bool>, location: Binding<String>, latitude: Binding<String>, longitude: Binding<String>) {
self.webView = WKWebView()
self.request = request
self._showingWebSheet = showingWebSheet
self._location = location
self._latitude = latitude
self._longitude = longitude
self.webView?.configuration.userContentController
.add(KakaoWebController(showingWebSheet: _showingWebSheet, location: _location, latitude: _latitude, longitude: _longitude), name: "callBackHandler")
}
...
}
그리고 데이터를 받아오는 함수가 KakaoWebController 내부에 있으니 저쪽으로 또 전달해준 후
키값으로 빼주면 된닷!
(처음에 몰라서 String으로 한 줄씩 뽑아왔지만,, 이렇게 간단했다니 ㅜ,ㅜ)
class KakaoWebController: NSObject, WKScriptMessageHandler {
@Binding var showingWebSheet: Bool
@Binding var location: String
@Binding var latitude: String
@Binding var longitude: String
init(showingWebSheet: Binding<Bool>, location: Binding<String>, latitude: Binding<String>, longitude: Binding<String>) {
self._showingWebSheet = showingWebSheet
self._location = location
self._latitude = latitude
self._longitude = longitude
}
// didReceive, 데이터 받아옴
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "callBackHandler", let data = message.body as? [String: Any] {
print("message name : \(message.name)")
print("post Message : \(message.body)")
print(data["jibunAddress"] as Any)
print(data["roadAddress"] as Any)
print(data["x"] as Any)
print(data["y"] as Any)
print(data["zonecode"] as Any)
if let roadAddress = (data["roadAddress"]) as? String {
location = roadAddress
}
if let roadLatitude = (data["x"]) as? String {
latitude = roadLatitude
}
if let roadLongitude = (data["y"]) as? String {
longitude = roadLongitude
}
print("Binding lacation: \(String(describing: location))")
print("Binding latitude: \(String(describing: latitude))")
print("Binding longitude: \(String(describing: longitude))")
showingWebSheet.toggle()
}
}
}
데이터를 선택하면 sheet가 닫히면서 원하는 Text 영역에 잘뜨는것 확인!
log
'PROGRAMMING CODE > SWIFT' 카테고리의 다른 글
[UIkit] Unable to activate constraint with anchors 오류 (0) | 2023.11.19 |
---|---|
[UIkit] button, sender title - nil value (0) | 2023.11.07 |
[SwiftUI] 다음(kakao) 주소찾기 part.2 (WKWebView, Sheet사용하기, Binding) (1) | 2023.10.19 |
[SwiftUI] 다음(kakao) 주소찾기 part.1 (WKWebView, 웹 통신) (1) | 2023.10.19 |
[SwiftUI] 채팅 기능 (타겟 뷰로 스크롤 이동하기, ScrollViewReader, ScrollTo, Anchor) (0) | 2023.10.12 |