Challenge: Encoding JSON Arrays | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/5429634-saving-data-in-ios/lessons/15

Hey @airjordan12345, my files don’t seem to be saving for some reason, and based on the video I believe I have the code correct.

Below is my TaskStore.swift file - what am I missing? When I run the app in the simulator, it loads the data fine. At runtime, I also see the console print out “I am saving tasks” which I have in the save method (I assume this is because we set the prioritizedTasks in the load method, which will trigger didSet). When I add a new tasks, I don’t see the print out so it looks like didSet isn’t being triggered.

What am I missing?

import Foundation
import Combine

class TaskStore: ObservableObject {
	let tasksJSONURL = URL(fileURLWithPath: "PrioritizedTasks", relativeTo: FileManager.documentsDirectoryURL).appendingPathExtension("json")

	
	@Published var prioritizedTasks: [PrioritizedTasks] = [] {
		didSet {
			saveJSONPrioritizedTasks()
		}
	}
  
	init() {
		loadJSONPrioritizedTasks()
	}
	
  func getIndex(for priority: Task.Priority) -> Int {
    prioritizedTasks.firstIndex { $0.priority == priority }!
  }
	
  // MARK: - Private Methods
  private func loadJSONPrioritizedTasks() {
        
    let decoder = JSONDecoder()
    
    do {
      let tasksData = try Data(contentsOf: tasksJSONURL)
			prioritizedTasks = try decoder.decode([TaskStore.PrioritizedTasks].self, from: tasksData)
		} catch let error {
      print(error)
    }
  }
	
	private func saveJSONPrioritizedTasks() {
		let encoder = JSONEncoder()
		encoder.outputFormatting = .prettyPrinted
		print("I am saving the tasks")
		
		do {
			let tasksData = try encoder.encode(prioritizedTasks)
			try tasksData.write(to: tasksJSONURL, options: .atomicWrite)
			
			
			
		} catch let error {
			print(error)
		}
	}
	
}

private extension TaskStore.PrioritizedTasks {
  init(priority: Task.Priority, names: [String]) {
    self.init(
      priority: priority,
      tasks: names.map { Task(name: $0) }
    )
  }
}

I also ran the project from the END folder and see the same results (the data isn’t getting saved). I’m on XCode 11.4.1

Hi Khuffie!

This actually turns out to be a bug in the recent Xcode releases. See my comment here:

The Swift site and bug tracker lists this as a fix that’s been implemented in Xcode 11.5 Beta. The alternatives you have right now are a workaround mentioned in that forum response, or using Xcode 11.5 Beta to ensure didSet gets called.

We are working on adding some author notes for future viewers who may run into this issue until it’s fixed and out in the wild :slight_smile:

Let me know if that helps and thank you for taking the time to follow the course!

@airjordan12345 ahh, I looked at the comments here but not in the next lesson. Good to know I’m not going crazy! :slight_smile: