-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathIterableKeychain.swift
More file actions
104 lines (79 loc) · 2.91 KB
/
IterableKeychain.swift
File metadata and controls
104 lines (79 loc) · 2.91 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
//
// Copyright © 2021 Iterable. All rights reserved.
//
import Foundation
class IterableKeychain {
init(wrapper: KeychainWrapper = KeychainWrapper()) {
self.wrapper = wrapper
}
var email: String? {
get {
let data = wrapper.data(forKey: Const.Keychain.Key.email)
return data.flatMap { String(data: $0, encoding: .utf8) }
}
set {
guard let token = newValue,
let data = token.data(using: .utf8) else {
wrapper.removeValue(forKey: Const.Keychain.Key.email)
return
}
wrapper.set(data, forKey: Const.Keychain.Key.email)
}
}
var userId: String? {
get {
let data = wrapper.data(forKey: Const.Keychain.Key.userId)
return data.flatMap { String(data: $0, encoding: .utf8) }
}
set {
guard let token = newValue,
let data = token.data(using: .utf8) else {
wrapper.removeValue(forKey: Const.Keychain.Key.userId)
return
}
wrapper.set(data, forKey: Const.Keychain.Key.userId)
}
}
var authToken: String? {
get {
let data = wrapper.data(forKey: Const.Keychain.Key.authToken)
return data.flatMap { String(data: $0, encoding: .utf8) }
}
set {
guard let token = newValue,
let data = token.data(using: .utf8) else {
wrapper.removeValue(forKey: Const.Keychain.Key.authToken)
return
}
wrapper.set(data, forKey: Const.Keychain.Key.authToken)
}
}
var deviceId: String? {
get {
let data = wrapper.data(forKey: Const.Keychain.Key.deviceId)
return data.flatMap { String(data: $0, encoding: .utf8) }
}
set {
guard let deviceId = newValue,
let data = deviceId.data(using: .utf8) else {
wrapper.removeValue(forKey: Const.Keychain.Key.deviceId)
return
}
wrapper.set(data, forKey: Const.Keychain.Key.deviceId)
}
}
// MARK: - PRIVATE/INTERNAL
private let wrapper: KeychainWrapper
private func encodeJsonPayload(_ json: [AnyHashable: Any]?) -> Data? {
guard let json = json, JSONSerialization.isValidJSONObject(json) else {
return nil
}
return try? JSONSerialization.data(withJSONObject: json)
}
private func decodeJsonPayload(_ data: Data?) -> [AnyHashable: Any]? {
guard let data = data else {
return nil
}
return try? JSONSerialization.jsonObject(with: data) as? [AnyHashable: Any]
}
}