teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

UserDefaultsへの保存と取り出しを追記

2021/09/28 05:34

投稿

退会済みユーザー
answer CHANGED
@@ -17,7 +17,10 @@
17
17
  if let userJSON = try? JSONEncoder().encode(user) {
18
18
  print(type(of: userJSON)) // Data
19
19
  // JSONEncoderの結果
20
+
20
- // userJSONをUserDefaultsに入れたい?
21
+ // userJSONをUserDefaultsに入れ
22
+ UserDefaults.standard.set(userJSON, forKey: "user")
23
+ UserDefaults.standard.synchronize() // 今すぐ同期する
21
24
  }
22
25
  }
23
26
  }
@@ -25,4 +28,15 @@
25
28
 
26
29
  print("SUCCESS LOGIN")
27
30
  ...
31
+ ```
32
+
33
+ 取り出す時:
34
+
35
+ ```swift
36
+ if let userJSON = UserDefaults.standard.data(forKey: "user") {
37
+ if let user = try? JSONDecoder().decode(User.self, from: userJSON) {
38
+ print(type(of: user)) // User
39
+ print(user.name) // test01
40
+ }
41
+ }
28
42
  ```