I'm currently working on a calendar within my application I'm writing using Swift. Although it works correctly in that data (event logs) can be entered and added to an array which will show up within a table view, once the application is closed down and removed from the background, when I re-open it, the event logs are gone.
Have I made any mistakes in my code?
import UIKit
import JTAppleCalendar
var event = [String]()
var userData = false
class CalendarViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var calendarView: JTAppleCalendarView!
@IBOutlet weak var monthAndYear: UILabel!
@IBOutlet weak var eventTable: UITableView!
override func viewDidAppear(_ animated: Bool) {
eventTable.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
configureCalendarView()
userData = UserDefaults.standard.bool(forKey: "userData")
if userData == true {
UserDefaults.standard.object(forKey: "event") //gets
}
else
{
event.append("NO USER DATA")
UserDefaults.standard.set(event, forKey: "event")
if event[0] == "NO USER DATA" {
event.remove(at: 0)
UserDefaults.standard.set(event, forKey: "event")
}
}
eventTable.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return event.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil)
cell.textLabel?.text = event[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete
{
event.remove(at: indexPath.row)
UserDefaults.standard.set(event, forKey: "event")
}
eventTable.reloadData()
}
Incase it's necessary here's the code which allows data to be entered in the array:
class AddEventViewController: UIViewController {
@IBOutlet weak var eventText: UITextField!
@IBAction func addEvent(_ sender: Any) {
userData = true
UserDefaults.standard.set(userData, forKey: "userData")
if eventText.text == ""
{
}
else
{
event.append(eventText.text!)
UserDefaults.standard.set(event, forKey: "event")
}
}
I've tried using the simulator and a real iOS devise along with re-installing Xcode, because I've read that it may be a problem with Xcode itself. I've also tried adding UserDefaults.standard.synchronize() all over the place, however, nothing seems to work.