티스토리 뷰

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
    }
댓글