我是swift的新手,我遇到了麻烦。所以我需要做的是将此数组保存为iphone的文档文件夹中的json文件。
var levels = ["unlocked", "locked", "locked"]
然后才能将其读回另一个数组。有人可以告诉我该怎么做?或提供完成此目的的确切代码。
EDITED: 我找到了一个例子。这是他们设置数据的方式:
"[ {"person": {"name":"Dani","age":"24"}}, {"person": {"name":"ray","age":"70"}} ]"
你可以这样访问它:
if let item = json[0]
{ if let person = item["person"]
{ if let age = person["age"]
{ println(age) } } }
但我需要能够从保存在文档文件夹中的文件中执行相同操作。
答案 0 :(得分:34)
如果你像我一样不喜欢使用全新的第三方框架只是为了这个简单的事情,这就是我在vanilla Swift中的解决方案。从在Documents文件夹中创建.json文件到将JSON写入其中。
let documentsDirectoryPathString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
let documentsDirectoryPath = NSURL(string: documentsDirectoryPathString)!
let jsonFilePath = documentsDirectoryPath.URLByAppendingPathComponent("test.json")
let fileManager = NSFileManager.defaultManager()
var isDirectory: ObjCBool = false
// creating a .json file in the Documents folder
if !fileManager.fileExistsAtPath(jsonFilePath.absoluteString, isDirectory: &isDirectory) {
let created = fileManager.createFileAtPath(jsonFilePath.absoluteString, contents: nil, attributes: nil)
if created {
print("File created ")
} else {
print("Couldn't create file for some reason")
}
} else {
print("File already exists")
}
// creating an array of test data
var numbers = [String]()
for var i = 0; i < 100; i++ {
numbers.append("Test\(i)")
}
// creating JSON out of the above array
var jsonData: NSData!
do {
jsonData = try NSJSONSerialization.dataWithJSONObject(numbers, options: NSJSONWritingOptions())
let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding)
print(jsonString)
} catch let error as NSError {
print("Array to JSON conversion failed: \(error.localizedDescription)")
}
// Write that JSON to the file created earlier
let jsonFilePath = documentsDirectoryPath.URLByAppendingPathComponent("test.json")
do {
let file = try NSFileHandle(forWritingToURL: jsonFilePath)
file.writeData(jsonData)
print("JSON data was written to teh file successfully!")
} catch let error as NSError {
print("Couldn't write to file: \(error.localizedDescription)")
}
答案 1 :(得分:19)
Array
保存为json文件以下Swift 3 / iOS 10代码显示了如何将Array
实例转换为json数据并使用FileManager
和{将其保存到位于iPhone文档目录中的json文件中{1}}:
JSONSerialization
作为替代方案,您可以实现以下使用流的代码:
func saveToJsonFile() {
// Get the url of Persons.json in document directory
guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileUrl = documentDirectoryUrl.appendingPathComponent("Persons.json")
let personArray = [["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]
// 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)
}
}
/*
Content of Persons.json file after operation:
[{"person":{"name":"Dani","age":"24"}},{"person":{"name":"ray","age":"70"}}]
*/
func saveToJsonFile() {
// Get the url of Persons.json in document directory
guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileUrl = documentDirectoryUrl.appendingPathComponent("Persons.json")
let personArray = [["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]
// Create a write-only stream
guard let stream = OutputStream(toFileAtPath: fileUrl.path, append: false) else { return }
stream.open()
defer {
stream.close()
}
// Transform array into data and save it into file
var error: NSError?
JSONSerialization.writeJSONObject(personArray, to: stream, options: [], error: &error)
// Handle error
if let error = error {
print(error)
}
}
/*
Content of Persons.json file after operation:
[{"person":{"name":"Dani","age":"24"}},{"person":{"name":"ray","age":"70"}}]
*/
以下Swift 3 / iOS 10代码显示了如何从位于iPhone文档目录中的json文件中获取数据,并使用Array
和{{Array
将其转换为FileManager
实例1}}:
JSONSerialization
作为替代方案,您可以实现以下使用流的代码:
/*
Content of Persons.json file:
[{"person":{"name":"Dani","age":"24"}},{"person":{"name":"ray","age":"70"}}]
*/
func retrieveFromJsonFile() {
// Get the url of Persons.json in document directory
guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileUrl = documentsDirectoryUrl.appendingPathComponent("Persons.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: [String: String]]] else { return }
print(personArray) // prints [["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]
} catch {
print(error)
}
}
位于Github的Save-and-read-JSON-from-Playground回购中的Playground展示了如何将Swift /*
Content of Persons.json file:
[{"person":{"name":"Dani","age":"24"}},{"person":{"name":"ray","age":"70"}}]
*/
func retrieveFromJsonFile() {
// Get the url of Persons.json in document directory
guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileUrl = documentsDirectoryUrl.appendingPathComponent("Persons.json")
// Create a read-only stream
guard let stream = InputStream(url: fileUrl) else { return }
stream.open()
defer {
stream.close()
}
// Read data from .json file and transform data into an array
do {
guard let personArray = try JSONSerialization.jsonObject(with: stream, options: []) as? [[String: [String: String]]] else { return }
print(personArray) // prints [["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]
} catch {
print(error)
}
}
保存到json文件中以及如何读取json文件并获取Swift Array
从它。
答案 2 :(得分:18)
我建议您使用SwiftyJSON框架。研究其文档,另外学习如何将字符串写入文件(提示:NSFileHandle
)
类似下面的代码,但你真的需要学习SwiftyJSON和NSFileHandle来学习如何将JSON数据序列化到文件并解析文件中的JSON数据
let levels = ["unlocked", "locked", "locked"]
let json = JSON(levels)
let str = json.description
let data = str.dataUsingEncoding(NSUTF8StringEncoding)!
if let file = NSFileHandle(forWritingAtPath:path) {
file.writeData(data)
}
答案 3 :(得分:7)
在Swift 4中,它已经内置在JSONEncoder中。
let pathDirectory = getDocumentsDirectory()
try? FileManager().createDirectory(at: pathDirectory, withIntermediateDirectories: true)
let filePath = pathDirectory.appendingPathComponent("levels.json")
let levels = ["unlocked", "locked", "locked"]
let json = try? JSONEncoder().encode(levels)
do {
try json!.write(to: filePath)
} catch {
print("Failed to write JSON data: \(error.localizedDescription)")
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
您要编码的对象必须符合Encodable
协议。
阅读Apple's official guide,了解如何扩展可编码的现有对象。
答案 4 :(得分:0)
这是通用的Swift解决方案
我创建了一个允许轻松完成的泛型类
//
// OfflineManager.swift
//
//
// Created by Prashant on 01/05/18.
// Copyright © 2018 Prashant. All rights reserved.
//
import UIKit
class OfflineManager: NSObject {
static let sharedManager = OfflineManager()
let LocalServiceCacheDownloadDir = "LocalData"
// Replace case as your naming
enum WSCacheKeys {
case CampignList .
case CampignDetail(id:String)
case ScreenShotList
var value:String {
switch self {
case .CampignList:
return "CampignList"
case .CampignDetail(let id):
return id
case .ScreenShotList :
return "ScreenShotList"
}
}
}
func getBaseForCacheLocal(with fileName:String) -> String? {
let filePath = FileManager.default.getDocumentPath(forItemName: self.LocalServiceCacheDownloadDir)
if FileManager.default.directoryExists(atPath: filePath) {
return filePath.stringByAppendingPathComponent(fileName)
} else {
if FileManager.default.createDirectory(withFolderName: self.LocalServiceCacheDownloadDir) {
return filePath.stringByAppendingPathComponent(fileName)
}
}
return nil
}
//------------------------------------------------------------
@discardableResult
func cacheDataToLocal<T>(with Object:T,to key:WSCacheKeys) -> Bool {
let success = NSKeyedArchiver.archiveRootObject(Object, toFile: getBaseForCacheLocal(with: key.value)!)
if success {
print( "Local Data Cached\(String(describing: getBaseForCacheLocal(with: key.value)))")
} else {
print("Error")
}
return success
}
//------------------------------------------------------------
func loadCachedDataFromLocal<T>(with key:WSCacheKeys ) -> T? {
return NSKeyedUnarchiver.unarchiveObject(withFile: getBaseForCacheLocal(with: key.value)!) as? T
}
//------------------------------------------------------------
func removeAllCacheDirs () {
do {
try FileManager.default.removeItem(atPath: self.getBaseForCacheLocal(with: "")!)
} catch {
print("error in remove dir \(error.localizedDescription)")
}
}
//--------------------------------------------------------------------------------
}
以下是extension FileManager
public var getDocumentDirectoryPath: String {
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
return documentDirectory
}
public func getDocumentPath(forItemName name: String)-> String {
return getDocumentDirectoryPath.stringByAppendingPathComponent(name)
}
public func directoryExists(atPath filePath: String)-> Bool {
var isDir = ObjCBool(true)
return FileManager.default.fileExists(atPath: filePath, isDirectory: &isDir )
}
public func createDirectory(withFolderName name: String)-> Bool {
let finalPath = getDocumentDirectoryPath.stringByAppendingPathComponent(name)
return createDirectory(atPath: finalPath)
}
这是String扩展的方法
public func stringByAppendingPathComponent(_ path: String) -> String {
let fileUrl = URL.init(fileURLWithPath: self)
let filePath = fileUrl.appendingPathComponent(path).path
return filePath
}
如何使用它?
保存
OfflineManager.sharedManager.cacheDataToLocal(with: object as! [String:Any], to: .CampignList)
阅读数据
DispatchQueue.global().async {
// GET OFFLINE DATA
if let object:[String:Any] = OfflineManager.sharedManager.loadCachedDataFromLocal(with: .CampignList) {
do {
let data = try JSONSerialization.data(withJSONObject: object, options: [])
let object = try CampaignListResponse.init(data: data)
self.arrCampignList = object.data ?? []
DispatchQueue.main.async {
self.tableVIew.reloadData()
}
} catch {
}
}
}
注意:您可以为json的类型定义自己的WSCacheKeys
,例如我正在获取一些广告系列列表
答案 5 :(得分:0)
以下是 Swift 4.2 中Isuru的答案。这可以在操场上工作:
let documentsDirectoryPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let documentsDirectoryPath = NSURL(string: documentsDirectoryPathString)!
let jsonFilePath = documentsDirectoryPath.appendingPathComponent("test.json")
let fileManager = FileManager.default
var isDirectory: ObjCBool = false
// creating a .json file in the Documents folder
if !fileManager.fileExists(atPath: (jsonFilePath?.absoluteString)!, isDirectory: &isDirectory) {
let created = fileManager.createFile(atPath: jsonFilePath!.absoluteString, contents: nil, attributes: nil)
if created {
print("File created ")
} else {
print("Couldn't create file for some reason")
}
} else {
print("File already exists")
}
// creating an array of test data
var numbers = [String]()
for i in 0..<100 {
numbers.append("Test\(i)")
}
// creating JSON out of the above array
var jsonData: NSData!
do {
jsonData = try JSONSerialization.data(withJSONObject: numbers, options: JSONSerialization.WritingOptions()) as NSData
let jsonString = String(data: jsonData as Data, encoding: String.Encoding.utf8)
print(jsonString as Any)
} catch let error as NSError {
print("Array to JSON conversion failed: \(error.localizedDescription)")
}
// Write that JSON to the file created earlier
// let jsonFilePath = documentsDirectoryPath.appendingPathComponent("test.json")
do {
let file = try FileHandle(forWritingTo: jsonFilePath!)
file.write(jsonData as Data)
print("JSON data was written to teh file successfully!")
} catch let error as NSError {
print("Couldn't write to file: \(error.localizedDescription)")
}