Learning Time : 1h 40min

My Github : Hot Prospects Source Code

My Note index link

day85.png

KeyWords

Challenge

  1. Add an icon to the “Everyone” screen showing whether a prospect was contacted or not.
ForEach(filterProspects) { prospect in
    HStack {
        VStack(alignment: .leading) {
            Text(prospect.name)
                .font(.headline)
            Text(prospect.emailAddress)
                .foregroundColor(.secondary)
        }
        Spacer()
        
        if filter == .none {
            Image(systemName: prospect.isContacted ? "person.crop.circle.fill.badge.checkmark" :  "person.crop.circle.badge.xmark")
                .foregroundColor(prospect.isContacted ? .green : .red)
        }
    }
}
  1. Use JSON and the documents directory for saving and loading our user data.
extension FileManager {
    static var documentsDirectory: URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        
        return paths[0]
    }
}

class Prospect: Identifiable, Codable {
    var id = UUID()
    var name = "Paul Hudson"
    var emailAddress = "[email protected]"
    fileprivate(set) var isContacted = false
    var create_time: Date = Date.now
}

@MainActor class Prospects: ObservableObject {
    @Published private(set) var people: [Prospect]
    let filePath: URL
    let locationFileName = "contacte.json"
    
    init() {
        self.filePath = FileManager.documentsDirectory.appendingPathComponent(locationFileName)
        
        do {
            let decoder = JSONDecoder()
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            decoder.dateDecodingStrategy = .formatted(formatter)
            
            let data = try Data(contentsOf: self.filePath)
            people = try decoder.decode([Prospect].self, from: data)
            return
        } catch {
            print("Unable to load data. \\(error.localizedDescription)")
        }
        
        people = []
    }
    
    func add(_ prospect: Prospect) {
        people.append(prospect)
        save()
    }
    
    func toggle(_ prospect: Prospect) {
        objectWillChange.send()
        prospect.isContacted.toggle()
        save()
    }
    
    private func save() {
        do {
            let encoder = JSONEncoder()
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            encoder.dateEncodingStrategy = .formatted(formatter)
            
            let data = try encoder.encode(people)
            try data.write(to: self.filePath, options: [.atomicWrite, .completeFileProtection])
        } catch {
            print("Unable to save data. \\(error.localizedDescription)")
        }
    }
}
  1. Use a confirmation dialog to customize the way users are sorted in each tab – by name or by most recent.