In some ways, this code worked perfectly because it toggled on and off. Sometimes it works fine, sometimes it crashes, and sometimes it works perfectly. Could you please tell me what went wrong with this code?
func downloadExchangeRateFromPast(toDate: Date, fromCurrency: String) {
startupCheck_ExchangeRateFromPast.enter()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let fromDate = dateFormatter.string(from: toDate)
let url = "https://api.exchangerate.host/convert?from=\(currentCurrency)&to=\(fromCurrency)&date=\(fromDate)"
let session = URLSession(configuration: .default)
session.dataTask(with: URL(string: url)!) { (data, response, _) in
guard let JSONData = data else {
startupCheck_ExchangeRateFromPast.leave()
return
}
if let response = response as? HTTPURLResponse { print("Exchange Status: \(response.statusCode)") }
do {
let finalData = try JSONDecoder().decode(ExchangeRatePastJSON.self, from: JSONData)
let newExchangeRate = ExchangeRateConvert(context: contextDataCore)
newExchangeRate.date = toDate
newExchangeRate.fromCode = fromCurrency
newExchangeRate.toCode = currentCurrency
newExchangeRate.rateConvert = finalData.result
let newExchangeHistoryRecord = ExchangeHistoryRecord(context: contextDataCore) // Thread 20: signal SIGABRT
newExchangeHistoryRecord.finalRecord = "\(toDate) - \(fromCurrency) - \(currentCurrency)"
try contextDataCore.save()
startupCheck_ExchangeRateFromPast.leave()
} catch { startupCheck_ExchangeRateFromPast.leave() }
}
.resume()
}