我的数据正在写入Firebase数据库,但我无法理解为什么?

时间:2015-06-19 19:28:20

标签: json database macos swift firebase

我是swift和数据库的新手。我想要做的就是从我的firebase数据库中读取。我使用此处提供的示例代码:https://www.firebase.com/docs/ios/guide/retrieving-data.html。 我在覆盖功能viewDidLoad(){}

中的viewcontroller.swift文件中调用了这个
func getRootRef(){
        // Read data and react to changes
        println("entered getRootRef")
        myRootRef.observeEventType(.Value, withBlock: { snapshot in
            println("value1")
            println(String(stringInterpolationSegment: snapshot.value))
            println("value2")
            }, withCancelBlock: { error in
                println(error.description)
                println("error")
        })
        println("left getRootRef")
}

输出:

entered getRootRef
left getRootRef
ViewController3
ViewController4
value1
(Function)
value2

我不明白为什么"(功能)"正在打印而不是我的数据。读取和写入权限都设置为true。我正在制作Mac应用程序。

1 个答案:

答案 0 :(得分:3)

您的代码示例并未提供有关您要执行的操作的足够信息 - 但是,假设您要打印出myRootRef节点的内容...

我相信在Swift中,FDataSnapshot.value被认为是可选的 - 它可以包含一个值,也可以是nil。因此我们需要打开值:

myRootRef.observeEventType(.Value, withBlock: { snapshot in     
   println( snapshot.value()! )          
})

!是一个强制展开变量,所以它必须包含一个值。在打印之前应检查nil,否则会导致运行时错误。

这可能更安全

myRootRef.observeEventType(.Value, withBlock: { snapshot in
    if let value: AnyObject = snapshot.value() {
        println(value)
    }  
})

请注意,snapshot.value可能包含许多不同对象之一:返回的数据类型:* NSDictionary * NSArray * NSNumber(还包括布尔值)* NSString