Noah-1
Noah-1

Reputation: 396

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 = components.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()

    commentRef.setValue([

        "Comment": trimmedComment,
        "Date": todaysDate

    ])

    self.delegate?.commentSubmitted(true)//delegate
    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.

Upvotes: 1

Views: 1825

Answers (2)

Özgür Ersil
Özgür Ersil

Reputation: 7013

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 !

commentRef.setValue([
        "Comment": trimmedComment!,
        "Date": todaysDate!
 ])

Upvotes: 1

Dravidian
Dravidian

Reputation: 9945

Make sure getRef! is a proper node name, And then change the todaysDate to

let todaysDate = "\(day!) \(monthSymbol!),\(year!)"

Upvotes: 1

Related Questions