Firebase setValue在IOS 10,Swift 3中无效

时间:2016-10-18 02:16:30

标签: ios swift firebase firebase-realtime-database exc-bad-access

当我尝试将评论保存到Firebase时,我的应用程序崩溃了。此代码在Xcode 8更新之前完美运行:

    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

}

显然错误是当我尝试使用" setValue"设置这些键值对。任何想法为什么会发生这种情况?

提前致谢。

2 个答案:

答案 0 :(得分:1)

确保getRef!是正确的节点名称,然后将 todaysDate 更改为

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

答案 1 :(得分:1)

Firebase不接受optional类型作为值

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

尝试用trimmedComment

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