static func readFile<T: Codable>(fileUrl:URL, decodeData: T.Type) -> T? {
do {
let data = try Data(contentsOf: fileUrl)
let decoder = JSONDecoder()
let result = try decoder.decode(T.self, from: data)
return result
} catch {
print("JSON : \(error.localizedDescription)")
return nil
}
}
let bundleJson = MyFileManager.readFile(fileUrl: bundleUrl, decodeData: [[QuestionData]].self)
어떤 타입을 넣어도
그 타입이 배열로 감싸져 잇어도 디코딩이 가능하다.
static func writeFile<T: Codable>(fileUrl: URL, data: T, complete:(Bool) -> Void) {
do {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted // 보기 좋게 저장 (선택사항)
let encodedData = try encoder.encode(data)
try encodedData.write(to: fileUrl)
print("파일 저장 성공: \(fileUrl)")
complete(true)
} catch {
print("JSON 저장 실패: \(error.localizedDescription)")
complete(false)
}
}
어떤 타입도 인코딩 가능
'swift' 카테고리의 다른 글
[viewDidLayoutSubviews] 뷰 크기가 결정된 후에 레이아웃 조정이 필요할 때 (0) | 2025.05.01 |
---|---|
스택 뷰로 다이나믹하게 뷰 height 늘렸다 줄이는 법 (0) | 2025.04.29 |
[tapGesture.cancelsTouchesInView = false] <- 이게 뭔데 (1) | 2025.04.28 |
[Swift] Codable 이해하기 (0) | 2025.04.27 |
UIView의 draw(_:)는 그림을 그리는 함수이다. (0) | 2025.04.18 |