The function below is called every 3 seconds and looks like:
func fetchItems(){
let url = URL(string: itemUrl)!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("Item \(self.item)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request, completionHandler: parseJasonObject)
task.resume()
}
func parseJasonObject(data: Data?, urlResponse: URLResponse?, error: Error?){
guard error == nil else {
print("error: \(error!)")
return
}
guard let content = data else{
print("No data")
return
}
if let decodedResponse = try? JSONDecoder().decode([itemdata]?.self, from: content) {
// we have good data – go back to the main thread
DispatchQueue.main.async {
self.items = decodedResponse
self.dataHasLoaded = true // state variable that determines whether or not data has been loaded
}
}
}
If I comment out the request.addValue() line, it causes the calendar to not exhibit a strange glitch where if you navigate the calendar to a new month or different date, when the above function runs, it reverts the calendar to it's starting screen (showing the current date). The calendar looks like:
@State private var selectedStartTime = Date()
let timer = Timer.publish(every: 3, on: .main, in: .common).autoconnect()
HStack {
Spacer()
DatePicker("", selection: self.$selectedStartTime, in: Date()...) //where self.$selectedStartTime is just a variable that is defined by the date/time the user selected
.datePickerStyle(GraphicalDatePickerStyle())
Spacer()
}
https://www.youtube.com/watch?v=ns9XXgrmiZk
As you can see, if I go to another month without selecting a date in that month, when the fetchEvents() function is run--it runs every 3 seconds inside an onReceive--it causes the calendar to go back to the currently selected day. If I select a new day in a different month, this is a non-issue. Any help would be greatly appreciated.