티스토리 뷰
https://ios-development.tistory.com/702
[iOS - swift] UserDefaults에 struct 형태 저장 방법 (“Attempt to insert non-property list object” 오류, UserDefaults
UserDefaults를 이해하기 위한 기본 지식 Byte buffer: 연속적으로 할당된 raw bytes를 저장하는 역할 random access가 가능하여 데이터를 key-value쌍으로 저장하고 로드할때 용이 보통 스위프트에서 메모리나
ios-development.tistory.com
위 글을 참고하여 작성하였습니다.
*이번 포스트는 제가 공부용으로 올린 거라 별다른 설명없이 코드만 올린 글입니다.*
///(동영상 번호, 진행상황)
struct MyVideo : Codable{
let num : Int
let progress : Double
}
// 현재 상태 저장
static func saveMyVideoProgress(videoNum: Int, progress : Double){
let newData = MyVideo(num: videoNum, progress: progress)
if let encoded = try? JSONEncoder().encode(newData) {
UserDefaults.standard.setValue(encoded, forKey: "user_video_current")
}
}
// 현재 저장 상태 가져오기
static func getMyVideoProgress()-> MyVideo?{
if let getValues = UserDefaults.standard.object(forKey: "user_video_current") as? Data {
let decoder = JSONDecoder()
if let savedObject = try? decoder.decode(MyVideo.self, from: getValues) {
return savedObject
}
}
return nil
}
'iOS개발 > Swift 기본' 카테고리의 다른 글
Swift 스와이프 기능 넣기 (UISwipeGestureRecognizer) (0) | 2023.04.21 |
---|---|
Swift 날짜 변화 이벤트 처리 (significantTimeChangeNotification) (0) | 2023.04.17 |
Swift Scrollview AutoScroll 만들기 (0) | 2023.03.14 |
Swift 알림창(UIAlertController) font 적용하기 (0) | 2023.03.09 |
Swift Side Menu UI 만들기 (with Code) (0) | 2023.02.06 |
댓글