Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- httpcookie
- 빗버켓
- wwdc24\
- navigationaction
- BFS
- 애러처리
- 콜드픽스
- 쿠키
- scenedelegate
- 연결
- 알고리즘
- 데이터장소
- atlasian
- swiftdata
- IOS
- om-4ti
- decidepolicyfor
- 24
- 빝버켓
- WWDC
- xcode
- Swift
- 옆집
- 2024
- 스위프트
- dfs
- 데이터구조
- JSON
- infoplist
- persistence
Archives
- Today
- Total
내가 iOS 개-발자라니.
옆집 스위프트: Swift Cookie 종속성 본문
백그라운드로 보낸뒤 오랜 시간 동안 inactive 상태였지만 완전히 종료되지 않은채 켜지면 쿠키가 다른활동들에 밀려 웹뷰를 못불러오는 상황이 판단되었다.
그래서 SceneDelegate에 넣기위해 아래 HTTPCookieStorage Extension을 추가하고 값을 UserDefault에 저장해 다시 보내는 방식을 적용해 보았다.
HTTPCookieStore Extension:
import Foundation
extension HTTPCookieStorage {
// 현재의 쿠키값을 삭제
static func clear() {
if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
}
}
// 현재 쿠키값을 가져와 UserDefaults에 저장
static func save() {
var cookies = [[HTTPCookiePropertyKey: Any]]()
if let newCookies = HTTPCookieStorage.shared.cookies {
for newCookie in newCookies {
var cookie = [HTTPCookiePropertyKey: Any]()
cookie[.name] = newCookie.name
cookie[.value] = newCookie.value
cookie[.domain] = newCookie.domain
cookie[.path] = newCookie.path
cookie[.version] = newCookie.version
if let date = newCookie.expiresDate {
cookie[.expires] = date.timeIntervalSince1970
}
cookies.append(cookie)
}
UserDefaults.standard.setValue(cookies, forKey: "cookies")
UserDefaults.standard.synchronize()
}
print("###cookie saved: \(cookies)")
}
// UserDefaults에 저장된 쿠키값을 불러와 set
static func restore() {
if let storedCookies = UserDefaults.standard.value(forKey: "cookies") as? [[HTTPCookiePropertyKey: Any]] {
for storedCookie in storedCookies {
var cookieProperties = storedCookie
if let expiresTimeInterval = storedCookie[.expires] as? TimeInterval {
cookieProperties[.expires] = Date(timeIntervalSince1970: expiresTimeInterval)
}
if let cookie = HTTPCookie(properties: cookieProperties) {
HTTPCookieStorage.shared.setCookie(cookie)
print("=== cookie loaded: \(cookie)")
}
}
print("###cookie restored: \(storedCookies)")
}
}
}
그리고
SceneDelegate 호출:
func sceneWillEnterForeground(_ scene: UIScene) {
print("foreground")
if window?.rootViewController is WebViewController {
HTTPCookieStorage.restore()
}
}
func sceneDidEnterBackground(_ scene: UIScene) {
print("background")
if window?.rootViewController is WebViewController {
HTTPCookieStorage.save()
}
}
'This is da(大) SWIFT' 카테고리의 다른 글
옆집 스위프트: 1-2) 데이터 구조 - 문자열(String) (0) | 2025.03.11 |
---|---|
옆집 스위프트: 1-1) 데이터 구조 - 배열(Array) (0) | 2025.03.10 |
옆집 스위프트: 웹뷰 에러코드 처리 (0) | 2024.07.02 |
옆집 스위프트: WWDC 24 SwiftData 커스텀 데이터 저장소 예제 (0) | 2024.06.26 |
옆집 스위프트: SwiftData와 Core Data의 차이점 (0) | 2024.06.26 |