SwiftUI extension Bundle for parse JSON file All In One
SwiftUI extension Bundle for parse JSON file All In One
JSONDecoder
//
// CodableBundle.swift
// PlacesOfInterest
//
// Created by xgqfrms on 2022/6/1.
//
import Foundation
// 扩展原有的 Bundle ✅
extension Bundle {
// Extensions must not contain stored properties
// private let step1Error = "加载本地 json 文件 ❌";
// 解析 json 文件
func decode(_ fileName: String) -> [CoverModel] {
// 1. 加载本地 json 文件
guard let url = self.url(forResource: fileName, withExtension: nil) else {
let error = "加载本地 json 文件 ❌, fileName: \(fileName)";
print(error)
fatalError(error)
}
// 2. 读取数据
guard let data = try? Data(contentsOf: url) else {
let error = "读取数据 ❌, fileName: \(fileName)";
print(error)
fatalError(error)
}
// 3. 解析 JSON 数据
guard let json = try? JSONDecoder().decode([CoverModel].self, from: data) else {
let error = "解析 JSON 数据 ❌, fileName: \(fileName)";
print(error)
fatalError(error)
}
return json;
}
}
demo
<T: Decodable>
T.Type
-> T
T.self
extension Bundle {
// 泛型 T,动态类型
func decode<T: Decodable>(_ type: T.Type, from filename: String) -> T {
guard let json = url(forResource: filename, withExtension: nil) else {
fatalError("Failed to locate \(filename) in app bundle.")
}
guard let data = try? Data(contentsOf: json) else {
fatalError("Failed to load \(filename) from app bundle.")
}
let decoder = JSONDecoder();
guard let json = try? decoder.decode(T.self, from: data) else {
fatalError("Failed to decode \(filename) from app bundle.")
}
return json
}
}
// demo
let items = Bundle.main.decode([TourItem].self, from: "Tour.json")
API
A representation of the code and resources stored in a bundle directory on disk.
存储在磁盘上捆绑目录中的代码和资源的表示。
https://developer.apple.com/search/?q=swift+Bundle
https://developer.apple.com/documentation/foundation/bundle/
refs
https://www.hackingwithswift.com/articles/141/8-useful-swift-extensions
https://www.hackingwithswift.com/books/ios-swiftui/loading-resources-from-your-app-bundle
https://developer.apple.com/forums/thread/650158
https://github.com/apple/swift-package-manager/blob/main/Sources/Build/BuildPlan.swift#L577
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16336635.html
未经授权禁止转载,违者必究!