Noah 1 Noah 1 - 1 year ago 173
Swift Question

Firebase setValue not working in IOS 10, Swift 3

My app is crashing when I try to save a comment to Firebase. This code was working perfectly before the Xcode 8 update:

func saveNewComment(){

//get date
let date = Date()
let calendar = Calendar.current
let components = (calendar as NSCalendar).components([.day,.month,.year], from: date)

let year = components.year
let month = components.month
let day =

//format month
let dateFormatter: DateFormatter = DateFormatter()
let months = dateFormatter.shortMonthSymbols
let monthSymbol = months?[month!-1]
let todaysDate = "\(day) \(monthSymbol),\(year)"

//trim comment
let comment = textView.text
let trimmedComment = comment?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)

//save new comment
let commentRef = ref.child("Stores").child(getRef!).child("CommentArray").childByAutoId()


"Comment": trimmedComment,
"Date": todaysDate


self.dismiss(animated: true, completion: nil)//dismiss view


Apparently the error is when i try to use "setValue" to set those key value pairs. Any ideas why is this happening?

Thanks in advance.

Answer Source

Firebase does not accept an optional type as a value

let trimmedComment = comment?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) 

Try to unwrap trimmedComment and todaysDate value with !

        "Comment": trimmedComment!,
        "Date": todaysDate!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download