swift - 如何在本地 json 文件 iOS Swift 中写入数据?
问题描述
if let path = Bundle.main.path(forResource: "domaines", ofType: "json") {
if JSONSerialization.isValidJSONObject(dict){
do{
let rawData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
try rawData.write(to: URL(fileURLWithPath: path))
}catch{
}
}else{
}
}else{
print("file not present")
}
这是我使用的代码,但我无法将数据保存到本地 JSON 文件。
解决方案
好吧,我创建了一个类,您可以通过该类创建一个 JSON 文件,然后添加数据以绕过一个数组,您可以通过用新数据替换数据来更新它。如果您不明白任何内容,请查看我的代码并发表评论。
这很容易理解,也很容易实现。
// offlineJsonFileManager.swift
// BuzCard
//
// Created by ap00724 on 06/02/20.
// Copyright © 2020 ap00724. All rights reserved.
//
import Foundation
import UIKit
class offlineJsonFileManager: NSObject {
static let sharedManager = offlineJsonFileManager()
func saveToJsonFile(fileName:String,dict:[[String:Any]]) {
guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileUrl = documentDirectoryUrl.appendingPathComponent("\(fileName).json")
let personArray = dict
// Transform array into data and save it into file
do {
let data = try JSONSerialization.data(withJSONObject: personArray, options: [])
try data.write(to: fileUrl, options: [])
} catch {
print(error)
}
}
func retrieveFromJsonFile(fileName:String,completion:(Bool,[[String:Any]])->()) {
// Get the url of Persons.json in document directory
guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
completion(false,[["error":"file does not exist."]]);return }
let fileUrl = documentsDirectoryUrl.appendingPathComponent("\(fileName).json")
// Read data from .json file and transform data into an array
do {
let data = try Data(contentsOf: fileUrl, options: [])
guard let personArray = try JSONSerialization.jsonObject(with: data, options: []) as? [[String:Any]] else { return }
completion(true,personArray)
} catch {
print(error)
completion(false,[["error":"\(error)"]])
}
}
}
推荐阅读
- java - 内存缓存 (CaffeineCache) 能否在应用程序重新启动后继续存在?
- java - org.springframework.web.client.HttpClientErrorException:404 未找到
- apache - Apache2 + Symfony4 + 子文件夹 = 问题
- python - 没有使用 python 3.6 和 apache2 的名为 celery 的模块
- python - 将 Numpy 导入 Sublime Text 3
- ruby-on-rails - Rails 聊天应用程序的 FAYE_URL 值应该是多少?
- javascript - google-maps-react 中未显示标记
- python - 调用进程的getter返回无
- image - 如何在“cameraCalibrator”应用程序中使用命令行导入图像?
- matlab - 使用一个命令从矩阵中获取特定点