gpt4 book ai didi

ios - 将 json 数据保存在内部设备中

转载 作者:行者123 更新时间:2023-11-30 11:29:02 26 4
gpt4 key购买 nike

我的应用程序中有此代码:

struct ServerConnect {
enum Result<T> {
case succes(T)
case error(String)
}

typealias completionHandler = (Result<Data >) -> ()

func getJsonFromServer(parameters: String, completion: @escaping completionHandler) {
let fullUrlString = ApiConstans.fullPath + parameters
guard let url = URL(string: fullUrlString) else {
debugPrint("\(ErrorsLabels.ServerConnect01)")
return completion(.error("\(ErrorsLabels.ServerConnect01)"))
}

URLSession.shared.dataTask(with: url) { (data, response, error) in
guard error == nil else {
debugPrint("\(ErrorsLabels.ServerConnect02)")
return completion(.error("\(ErrorsLabels.ServerConnect02)"))
}

guard let data = data else {
debugPrint("\(ErrorsLabels.ServerConnect03)")
return completion(.error("\(ErrorsLabels.ServerConnect03)"))
}

debugPrint("R> \(fullUrlString)")
return completion(.succes(data))
}.resume()
}


func getJsonProducts(lang: String?, region: Int?, completion: @escaping completionHandler) {
self.getJsonFromServer(parameters: "?action=GET_PRODUCTS&lang=\(lang!)&region=\(region!)", completion: completion)
}

}

我想使用以下代码将数据保存到我的设备:

let cms = ServerConnect()
cms.getJsonProducts(lang: selectedLanguage, region: selectedRegion , completion: { (data) in
switch data {
case .succes(let data):
self.saveJsonFileToTheDisk(path: selectedLanguage + "/json/temp.json", downloadData: data)
case .error(let error):
self.errorLoginMessage(txt: "\(ErrorsLabels.MainViewControler01). \(error)", title: "Blad".localized())
break
}
})


func saveJsonFileToTheDisk(path: String, downloadData: Data){
do {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent(path)
try downloadData.write(to: fileURL, options: .atomic)
} catch { self.errorLoginMessage(txt: "\(ErrorsLabels.MainViewControler02). \(error)", title: "Blad".localized()) }
}

不幸的是,应用程序不会将文件保存到磁盘(甚至不会创建文件)。我有错误:

"The folder temp.json doesn't exist. UserInfo=PNSFilePath=Users/mymac/Library/Developer........./json/temp.json. .... No such file or directory ";

有谁知道这是什么问题吗?

最佳答案

您需要实际创建文件夹和文件,然后写入。

下面的代码检查该文件夹是否存在,如果不存在,则创建它。

然后它对文件执行相同的操作。

import UIKit

class ViewController: UIViewController {

let demoJson = """
{ "name": "John Smith" }
"""
let folderName = "json"
let fileName = "demo.json"
var isDir : ObjCBool = false
let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

override func viewDidLoad() {
super.viewDidLoad()


createFolderIfNotExists(name: folderName)
saveJson(json: demoJson, toFile: "/\(folderName)/\(fileName)")

let filePath = documentsDir.appendingPathComponent("/\(folderName)/\(fileName)")
fileExists = FileManager.default.fileExists(atPath: filePath.path)

print("[DEBUG] - File exits value: \(fileExists)")
print(try? String(contentsOf: filePath))
}

func createFolderIfNotExists(name: String) {
let path = documentsDir.appendingPathComponent(name)
if FileManager.default.fileExists(atPath: path.path, isDirectory: &isDir) {
return
} else {
do {
try FileManager.default.createDirectory(at: path, withIntermediateDirectories: false, attributes: nil)
} catch {
print(error)
}
}
}

func saveJson(json: String, toFile: String) {
let path = documentsDir.appendingPathComponent(toFile)
if FileManager.default.fileExists(atPath: path.path) {
return
}

if let data = json.data(using: .utf8), FileManager.default.createFile(atPath: path.path, contents: data, attributes: nil) {
try? data.write(to: path)
}
}
}

关于ios - 将 json 数据保存在内部设备中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50447528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com