美文网首页
如何保存日期date数据

如何保存日期date数据

作者: 王勋才 | 来源:发表于2021-10-15 22:38 被阅读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("时间")
            }

        }
    }
}



相关文章

网友评论

      本文标题:如何保存日期date数据

      本文链接:https://www.haomeiwen.com/subject/vorvoltx.html