I have the code to convert UTC datetime to the local datetime based on a given address and this function is a closure. I want to call this function in a map function to change all my UTC time in an array of structs to local datetime. Here is my code for the converting UTC to local datetime.
func getTimeZoneFrom(address: String, completion: @escaping(_ coordinate: String?, _ error: Error?) -> () ) { CLGeocoder().geocodeAddressString(address) { completion($0?.first?.timeZone?.identifier, $1) } } func calculateLocalDateTime(from date: String, identifier: String, using format: String) -> Date { let formatter = DateFormatter() formatter.locale = Locale.autoupdatingCurrent formatter.dateFormat = format if let date = formatter.date(from: date) { if let timeInterval = TimeZone.init(identifier: identifier)?.secondsFromGMT(for: date) { let localDateTime = Date(timeInterval: TimeInterval(timeInterval), since: date) return localDateTime } } else { print("Cannot get the date using the provided date format.\nPlease provide adequate date format.") return Date() } return Date() } func getLocalDateTime(date: String, address: String, completionHandler: @escaping ((Date) -> Void)) { getTimeZoneFrom(address: address) { (timeZoneIdentifier, error) in guard let identifier = timeZoneIdentifier, error == nil else { return } let localDateTime = calculateLocalDateTime(from: date, identifier: identifier, using: "yyyy-MM-dd'T'HH:mm:ss'Z'") completionHandler(localDateTime) } } func dateTimeUsingMediumFormat(provided dateTime: Date) -> String { return DateFormatter.localizedString(from: dateTime, dateStyle: .medium, timeStyle: .short) } Here is my attempt to apply this function in my map function.
struct LocationDateModel { var address: String var date: String init(address: String, date: String) { self.address = address self.date = date } } let models = [LocationDateModel(address: "Windsor, ON", date: "2021-01-07T19:27:54Z"), LocationDateModel(address: "Windsor, ON", date: "2021-01-07T21:54:54Z"), LocationDateModel(address: "Windsor, ON", date: "2021-01-08T00:36:56Z"), LocationDateModel(address: "Edmonton, AB", date: "2021-01-11T21:04:53Z"), LocationDateModel(address: "Edmonton, AB", date: "2021-01-12T15:56:19Z"), LocationDateModel(address: "Edmonton, AB", date: "2021-01-12T16:08:28Z")] let modifiedModels = models.map { model -> LocationDateModel in var temp = "" getLocalDateTime(date: model.date, address: model.address) { (value) in temp = dateTimeUsingMediumFormat(provided: value) } return LocationDateModel(address: model.address, date: temp) } https://stackoverflow.com/questions/67238176/calling-closure-in-map-function April 24, 2021 at 08:15AMHowever, this is return an empty string for date as declared in temp which means its returning the declaration of the variable but not going into the closure. How can I approach this.
没有评论:
发表评论