Swift-FileManager Extension
2018-05-15 本文已影响0人
长风浮云
通过给定的路径读取JSON文件
extension FileManager {
public func jsonFromFile(
atPath path: String,
readingOptions: JSONSerialization.ReadingOptions = .allowFragments) throws -> [String: Any]? {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let json = try JSONSerialization.jsonObject(with: data, options: readingOptions)
return json as? [String: Any]
}
}
通过给定的文件名读取JSON文件
extension FileManager {
public func jsonFromFile(
withFilename filename: String,
at bundleClass: AnyClass? = nil,
readingOptions: JSONSerialization.ReadingOptions = .allowFragments) throws -> [String: Any]? {
// https://stackoverflow.com/questions/24410881/reading-in-a-json-file-using-swift
let name = filename.components(separatedBy: ".")[0]
let bundle = bundleClass != nil ? Bundle(for: bundleClass!) : Bundle.main
if let path = bundle.path(forResource: name, ofType: "json") {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let json = try JSONSerialization.jsonObject(with: data, options: readingOptions)
return json as? [String: Any]
}
return nil
}
}
资源来自网络和日常整理,持续更新