I am retrieving a value from a remote json file through task in a function with a completion code (as recommended practice) where I retrieve a date. I then need to use that date in subsequent processing. In this case, return the date and continue my processing. I can work with the date with in the function (see below) but I can't get the value outside the function. Any help would be appreciated.
case .remote:
var fetchDate: Date?
fetchRemoteArticlesDate { date in
fetchDate = date
// finds the correct date
print("* fetchDate1: \(String(describing: fetchDate))" )
}
// How can I receive the date from fetchRemoteArticlesData so I can return it?
print("* fetchDate2: \(fetchDate ?? DateInfo.zeroDate)")
return fetchDate ?? DateInfo.zeroDate
class func fetchRemoteArticlesDate(completion: @escaping (Date) -> Void) {
let urlString = AppValues.articlesLocation.remote
let url = URL(string: urlString)!
let session = URLSession.shared
let task = session.dataTask(with: url) { (data, response, error) in
if let error = error {
LogEvent.print(module: "Articles.fetchArticles", message: "Error saving articles.json: \(error)")
DispatchQueue.main.sync {
completion(DateInfo.zeroDate)
}
return
}
guard let myData = data else {
LogEvent.print(module: "Articles.fetchArticles", message: "no JSON data received")
DispatchQueue.main.async {
completion(DateInfo.zeroDate)
}
return
}
let date = decodeArticlesDateV2(myData)
LogEvent.print(module: "Articles.articlesDate", message: "\(UserSettings.init().articlesLocation.description) date: \(date)")
completion(date)
}
task.resume()
}