728x90
1. ํ์ํ ๋ฐ์ดํฐ ๊ตฌ์กฐ๋ฅผ ๋ง์๋๋ก ๋ง๋ ๋ค
2. API ๋ช ์ธ์์ ๋ฐ๋ผ ๋ชจ๋ธ์ ๋ง๋ค๊ณ ํ๋ฉด์ ๊ตฌ์ฑํ๋ค.
2-1. ๋ชจ๋ธ์ ๊ตฌ์ฑํ๊ณ , ์์๋ก ๋๋ฏธ ๋ฐ์ดํฐ๋ฅผ ๋ง๋ ๋ค.
2-2. json ํ์ผ์ ์ด์ฉํด์ ํต์ ํ ๊ฒ์ฒ๋ผ ์ฒ๋ฆฌํ๋ค. (๊ฐ์ง ํต์ )
1. json ํ์ผ ์์ฑํ๊ธฐ
- strings File๋ก ์์ฑํ๊ณ .json ํ์ฅ์ ๋ถ์ฌ์ฃผ๊ธฐ! -> Use .json ํด๋ฆญ
[
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
"userId": 1,
"id": 3,
"title": "fugiat veniam minus",
"completed": false
},
{
"userId": 1,
"id": 4,
"title": "et porro tempora",
"completed": true
},
]
2. ๋ฐ์ดํฐ ๋ชจ๋ธ ์์ฑ
import Foundation
struct Todo: Codable {
let userId: Int
let id: Int
let title: String
let completed: Bool
}
3. Mock Parser ์์ฑํ๊ธฐ
- json์ ํ๋ก์ ํธ ๋ด์์ ์ฌ์ฉํ๋๋ก ๋ณํ ๊ณผ์
import Foundation
final class MockParser {
static func load<D: Codable>(_ type: D.Type, from resourceName: String) -> D? {
// type : ๋์ฝ๋ฉ ํ ๋ ์ฌ์ฉ๋๋ ๋ชจ๋ธ์ ํ์
// resourceName : json ํ์ผ์ ์ด๋ฆ
guard let path = Bundle.main.path(forResource: resourceName, ofType: "json") else {
return nil
}
// ํ์ฅ์๊ฐ json์ธ ํ์ผ์ ๊ฒฝ๋ก๋ฅผ ๊ฐ์ ธ์ค๋ ๋ถ๋ถ
guard let jsonString = try? String(contentsOfFile: path) else {
return nil
}
// ํ์ผ ์์ ์๋ ๋ฐ์ดํฐ(json)์ String ํํ๋ก ๊ฐ์ ธ์จ๋ค
print(jsonString)
let decoder = JSONDecoder()
let data = jsonString.data(using: .utf8)
// string ํํ๋ก ๊ฐ์ ธ์จ json์ dataํ์ผ๋ก ๋ณํ
print(data)
guard let data = data else { return nil }
return try? decoder.decode(type, from: data)
// data๋ฅผ swift ํํ๋ก ์ฌ์ฉํ๊ธฐ ์ํด decodingํ๋ ๊ณผ์
}
}
3. ์๋น์ค ์ฝ๋ ์์ฑํ๊ธฐ
import Foundation
final class TodoManager {
// service code
static let shared = TodoManager()
private init() {}
}
extension TodoManager {
func getTodoMock() -> [Todo] {
return MockParser.load([Todo].self, from: "Todo")!
}
}
728x90