반응형
WKWebView 쿠키(Cookie) 가이드
1. 개요
WKWebView는 내부적으로 별도 프로세스를 사용하기 때문에, URLSession의 쿠키와 자동으로 공유되지 않습니다.
즉, 네이티브 로그인 세션을 웹뷰에 전달하거나 반대로 웹뷰 로그인 상태를 앱에 반영하려면 수동 쿠키 동기화가 필요합니다.
2. 네이티브 → WebView 쿠키 주입
import WebKit
func injectCookies(_ cookies: [HTTPCookie], into webView: WKWebView, completion: @escaping () -> Void) {
let dataStore = webView.configuration.websiteDataStore
let dispatchGroup = DispatchGroup()
for cookie in cookies {
dispatchGroup.enter()
dataStore.httpCookieStore.setCookie(cookie) {
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
completion()
}
}
사용 예시:
if let cookies = HTTPCookieStorage.shared.cookies {
injectCookies(cookies, into: webView) {
webView.load(URLRequest(url: URL(string: "https://example.com")!))
}
}
3. WebView → 네이티브 쿠키 읽기
func getCookies(from webView: WKWebView, completion: @escaping ([HTTPCookie]) -> Void) {
webView.configuration.websiteDataStore.httpCookieStore.getAllCookies { cookies in
completion(cookies)
}
}
사용 예시:
getCookies(from: webView) { cookies in
for cookie in cookies {
print("쿠키 이름: \(cookie.name), 값: \(cookie.value)")
}
}
4. URLSession과 쿠키 공유
let config = URLSessionConfiguration.default
let cookieStorage = HTTPCookieStorage.shared
config.httpCookieStorage = cookieStorage
config.httpCookieAcceptPolicy = .always
let session = URLSession(configuration: config)
getCookies(from: webView) { cookies in
cookies.forEach { HTTPCookieStorage.shared.setCookie($0) }
}
이렇게 하면 WKWebView 로그인 세션을 URLSession에서도 그대로 사용할 수 있습니다.
5. JavaScript로 쿠키 접근
let script = "document.cookie"
webView.evaluateJavaScript(script) { result, error in
print("document.cookie =", result ?? "")
}
⚠️ SameSite 정책으로 인해 iframe 내부 쿠키 접근은 제한될 수 있습니다.
6. 쿠키 및 캐시 초기화
func clearAllCookies() {
let store = WKWebsiteDataStore.default()
store.httpCookieStore.getAllCookies { cookies in
cookies.forEach { store.httpCookieStore.delete($0) }
}
}
let types = WKWebsiteDataStore.allWebsiteDataTypes()
WKWebsiteDataStore.default().removeData(ofTypes: types, modifiedSince: .distantPast) {
print("모든 웹 데이터 삭제 완료")
}
7. WKWebView 구성 (iOS 17+)
let config = WKWebViewConfiguration()
config.defaultWebpagePreferences.allowsContentJavaScript = true
config.websiteDataStore = .default()
let webView = WKWebView(frame: .zero, configuration: config)
- .default()는 쿠키 저장됨
- .nonPersistent()는 세션 쿠키 유지 안 됨
8. async/await 버전
func getCookiesAsync(from webView: WKWebView) async -> [HTTPCookie] {
await withCheckedContinuation { continuation in
webView.configuration.websiteDataStore.httpCookieStore.getAllCookies { cookies in
continuation.resume(returning: cookies)
}
}
}
9. 자주 발생하는 문제 요약
| 문제 | 원인 | 해결 |
| 쿠키가 안 넘어감 | setCookie 시점보다 load 호출이 빠름 | 주입 완료 후 load |
| document.cookie 접근 안됨 | SameSite 또는 iFrame 제한 | WKHTTPCookieStore 사용 |
| 세션 유지 안됨 | nonPersistent store 사용 | .default() store 사용 |
| 앱 재시작 시 쿠키 사라짐 | 앱 종료 시 WebView 쿠키 미보존 | UserDefaults로 쿠키 수동 저장 |
10. 결론 요약
| 목표 | 방법 |
| 네이티브 → WebView 쿠키 전달 | setCookie() |
| WebView → 네이티브 쿠키 복사 | getAllCookies() |
| URLSession 공유 | HTTPCookieStorage.shared 동기화 |
| 세션 종료 | removeData(ofTypes:modifiedSince:) |
✅ WKHTTPCookieStore를 사용하면 안정적으로 쿠키를 동기화할 수 있습니다.
핵심은 쿠키 주입 타이밍과 DataStore 일관성 유지입니다.
반응형
'Dev Study > iOS' 카테고리의 다른 글
| Swift Concurrency — 구조적 동시성 완전 이해 (0) | 2025.11.14 |
|---|---|
| 메모리 누수 방지 — weak / unowned 정확히 사용하기 (0) | 2025.11.14 |
| UIKit ↔ SwiftUI 혼용 시 Life-Cycle 이해하기 (0) | 2025.11.14 |
| ViewController 비만화 방지 — 비즈니스 로직 분리 (0) | 2025.11.14 |
| 화면을 이미지로 전환 (UIView -> UIImage, View -> Image) (0) | 2025.11.06 |
| WKWebView 실전 팁 모음 (iOS 15+) (0) | 2025.11.06 |
| Swift 날짜 포맷(DateFormatter) 치트시트 & 사용법 정리 (iOS) (0) | 2025.11.06 |
| iOS 위젯에서 앱 특정 화면으로 이동하는 방법 (0) | 2025.11.06 |


