脱机时从FileManager检索保存的信息

Within my ViewController I have the below. By using breakpoints & print statements I can see that I am saving the data correctly. How can I use my getItemsFromDisk function here to call on saved data when a user loses their internet connection? I've attempted to call an if/else statement for loading this data from the function before attempting the if let url line, this results in no data being received at all.

override func viewDidLoad() {
      super.viewDidLoad()
      let urlString = "https://fakeapitesturl.com"
      DispatchQueue.global(qos: .userInitiated).async {
          [weak self] in
          if let url = URL(string: urlString) {
              if let data = try? Data(contentsOf: url) {
                  self?.parse(json: data)
              }
          }
      }
  }

  func parse(json: Data) {
      let decoder = JSONDecoder()
      if let jsonItems = try? decoder.decode(Items.self, from: json) {
          items = jsonItems.data
          saveItemsToDisk(items: items)
          DispatchQueue.main.async { [weak self] in
              self?.tableView.reloadData()
          }
      }
  }

struct Items: Codable {
    let data: [Item]
}

我具有以下功能来保存/加载数据:

import Foundation

func getDocumentsURL() -> URL {
    if let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
        return url
    } else {
        fatalError("Could not retrieve documents directory")
    }
}

func saveItemsToDisk(items: [Item]) {
    let url = getDocumentsURL().appendingPathComponent("items.json")
    let encoder = JSONEncoder()
    do {
        let data = try encoder.encode(items)
        try data.write(to: url, options: [])
    } catch {
        fatalError(error.localizedDescription)
    }
}

func getItemsFromDisk() -> [Item] {
    let url = getDocumentsURL().appendingPathComponent("items.json")

    let decoder = JSONDecoder()
    do {
        let data = try Data(contentsOf: url, options: [])
        let items = try decoder.decode([Item].self, from: data)
        return items
    } catch {
        fatalError(error.localizedDescription)
    }
}

TIA寻求帮助

评论
  • 偷偷恋NI
    偷偷恋NI 回复

    你有尝试过吗?

    if let data = try? Data(contentsOf: url) {
                      self?.parse(json: data)
                  } else {
        items = getItemsFromDisk() 
        DispatchQueue.main.async { [weak self] in
              self?.tableView.reloadData()
          }
    }