当我尝试在Firebase数据库上插入Date as Key时崩溃

时间:2017-09-05 16:48:19

标签: ios swift firebase firebase-realtime-database

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

之下

的AppDelegate:

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
    }

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

  

以NSException类型的未捕获异常终止

的ViewController:

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"])
    }

1 个答案:

答案 0 :(得分:1)

我认为你的问题就在这一行:

let date = Date().timeIntervalSince1970

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

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

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

尝试这样做:

  1. 从日期

  2. 中提取DateComponents
  3. 使用结果

  4. 创建一个新字符串

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

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