반응형
iOS 14 이상부터는 UserDefault 대신에 AppStorage를 사용할수가 있지만,
@AppStorage를 사용할때 Date 타입이나 Array는 기본적으로 지원하지 않습니다.
이를 사용하기 위해서는 다음과 같이 String 타입으로 변환해서 사용할 수 있습니다.
// @AppStorage에 Date 타입을 지원하지 않기에 문자열로 사용
extension Date: RawRepresentable {
private static let formatter = ISO8601DateFormatter()
public var rawValue: String {
Date.formatter.string(from: self)
}
public init?(rawValue: String) {
self = Date.formatter.date(from: rawValue) ?? Date()
}
}
// @AppStorage에 Array 타입을 지원하지 않기에 문자열로 사용
extension Array: RawRepresentable where Element: Codable {
public init?(rawValue: String) {
guard let data = rawValue.data(using: .utf8),
let result = try? JSONDecoder().decode([Element].self, from: data)
else {
return nil
}
self = result
}
public var rawValue: String {
guard let data = try? JSONEncoder().encode(self),
let result = String(data: data, encoding: .utf8)
else {
return "[]"
}
return result
}
}
사용방법은 다음과 같습니다.
// 날짜 저장
@AppStorage("Today") var today = Date()
// 배열 저장
@AppStorage("Array") var array = [1, 2, 3, 4]
반응형
'개발 > iOS' 카테고리의 다른 글
TextField에 clearButton 추가하기 (0) | 2023.12.13 |
---|---|
Warning "Non-constant range: argument must be an integer literal" (0) | 2023.12.07 |
SFSymbol의 Monochrome, Hierarchical, Palette, Multicolor Mode (1) | 2023.12.05 |
Custom Environment (1) | 2023.12.05 |
PassthroughSubject vs CurrentValueSubject (1) | 2023.12.01 |
UIView -> UIImage (0) | 2023.11.15 |
iOS 16.4 이후부터 WebView 디버깅 하기 (0) | 2023.11.15 |
iOS App URL Cache 제거 (0) | 2023.11.10 |