ios - 当我尝试在 Firebase 数据库中插入日期作为键时崩溃

标签 ios swift firebase firebase-realtime-database

我正在根据我的文档配置我的数据库。我做了所有的初始配置:我将把代码放在下面

应用委托(delegate):

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()

        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
        GIDSignIn.sharedInstance().delegate = self
        FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

        if (Auth.auth().currentUser) != nil {
            presentHome()
        } else {
            presentSignIn()
        }

        return true
    }

问题是,当我创建数据库引用并插入某些内容时,出现此错误:

terminating with uncaught exception of type NSException

View Controller :

var ref: DatabaseReference!

    override func viewDidLoad() {
        super.viewDidLoad()
        ref = Database.database().reference()
    }

@IBAction func saveTask(_ sender: Any) {
        let task:[String:Any] = [
            "title":self.titleTxtField.text!,
            "type":type!,
            "observations":"Teste de tarefa",
            "finished":false,
            "images":[
                "image1":"https://static.pexels.com/photos/248797/pexels-photo-248797.jpeg",
                "image2":"http://www.planwallpaper.com/images#static/images/beautiful-sunset-images-196063.jpg"
                ]
        ]

        let date = Date().timeIntervalSince1970
        ref.child("\(self.user!.uid)/tasks/\(date)").setValue(["teste":"teste"])
    }

最佳答案

我认为你的问题出在这条线上:

let date = Date().timeIntervalSince1970

这会打印一些不允许在 Firebase 上作为子键输入的字符

所以,如果你想要这样的结构:

root
--- year
------ month
--------- day

尝试这样做:

  1. 从日期中提取 DateComponents

  2. 用结果创建一个新的字符串

并使用以下代码将新字符串添加为子字符串:

let components = Calendar.current.dateComponents([.day, .month, .year], from: yourDate)
let ref = Database.database().reference()
ref.child("root/\(components.year!)/\(components.month!)/\(components.day!)")

关于ios - 当我尝试在 Firebase 数据库中插入日期作为键时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46059830/

相关文章:

ios - 删除设置

swift - 我正在尝试创建一个 UIbarButtonItem,其宽度和高度等于导航栏高度的 70%?

javascript - 在 Firebase Cloud 函数中返回 XML

ios - [Firestore][I-FST000001] 无法到达 Firestore 后端

ios - 如何在特定位置的 uiimage View 上设置小图像?

iOS 约束样式 : addConstraints vs . isActive = true

ios - 如何使用 iOS 6 风格的嵌入 segue 配置嵌入式 View Controller

ios - 如何使用 AutoLayout 从 UIView 子类获取框架

ios - 将目标添加到 tableview 单元格内的 collectionview 单元格的按钮

firebase - 如何在本地配置 Firebase 功能的超时