首页 > 解决方案 > 如何在本地 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 文件。

标签: swift

解决方案


好吧,我创建了一个类,您可以通过该类创建一个 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)"]])
        }
    }
}

推荐阅读