如何保存日期date数据
2021-10-15 本文已影响0人
王勋才
//
// SaveDataTool.swift
// TestAppForIos
//
// Created by wangxuncai on 2021/10/15.
//
import Foundation
struct ThingItem:Identifiable,Hashable,Codable{
var id = UUID()
var dt:Date
}
class SaveDataTool:ObservableObject{
@Published var thing:ThingItem = ThingItem(dt: Date()) {
didSet{
self.saveData(forPathName: "myDate")
}
}
init(){
self.thing = getData(frompathName: "myDate")
}
func getData(frompathName:String)->ThingItem{
var result:ThingItem = ThingItem(dt: Date())
let decode = JSONDecoder()
if FileManager.default.fileExists(atPath: getURL(with: frompathName).path), let data = try? Data(contentsOf: getURL(with: frompathName)){
do {
let things = try decode.decode(ThingItem.self, from: data)
result = things
} catch {
print("get data failed ")
}
}
return result
}
func saveData(forPathName:String){
let encode = JSONEncoder()
let data = try? encode.encode(thing)
do {
try data?.write(to: getURL(with: forPathName))
} catch {
print("save data failed")
}
}
func getURL(with pathComponentName:String)->URL{
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let path = paths[0]
return path.appendingPathComponent(pathComponentName).appendingPathExtension("json")
}
}
//使用方法
import SwiftUI
struct ContentView: View {
@StateObject var vm = SaveDataTool()
var body: some View {
Form {
Text("\(vm.thing.dt)")
DatePicker(selection: self.$vm.thing.dt, displayedComponents: [.date,.hourAndMinute]) {
Text("时间")
}
}
}
}