Search code examples
swiftfirebaseeureka-forms

Swift converting Eureka date into String for firebase storing


I am attempting to collect the date value from a Eureka DateTimeRow to then store it into Firebase but to store it I would need it to be in a string format. I have attempted this conversion but I receive the error 'Could not cast value of type 'Foundation.Date' (0x108af27e8) to 'Swift.String' (0x1086e99f8).' I would like to know if there is something I am missing from my conversion method.

DateTimeRow:

<<< DateTimeRow("startDate"){
            $0.title = "Start Date"
            $0.value = NSDate() as Date
            $0.cellUpdate { (cell, row) in
                cell.datePicker.minimumDate = Date()
            }
                $0.onChange { row in
                    start = row.value!
            }

        }

Code getting the values of the Erueka form and converting:

let valuesDictionary = form.values()   
let formatter = DateFormatter()
                formatter.dateFormat = "yyyy-MM-dd"
                let formattedDate = formatter.date(from: valuesDictionary["startDate"] as! String)

Thank you all feedback welcomed.


Solution

  • As you want to convert from a Date (Eureka) to a String (Firebase), you should use the string(from:) method of the DateFormatter, whereas you are attempting to use the date(from:) method.

    // Date to String
    func string(from date: Date) -> String
    
    // String to Date
    func date(from string: String) -> Date?