我的数据正在写入 Firebase 数据库,但我无法读取它,为什么?
My data is being written to Firebase database but i can't read it why?
我是 swift 和数据库的新手。我要做的就是从我的 firebase 数据库中读取。我正在使用此处提供的示例代码:https://www.firebase.com/docs/ios/guide/retrieving-data.html。
我是从我的 viewcontroller.swift 文件中调用它的 override func viewDidLoad(){}
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
我不明白为什么打印的是“(Function)”而不是我的数据。读写权限都设置为 true。我正在制作 Mac 应用程序。
您的代码示例没有提供足够的信息来说明您想做什么 - 但是,假设您想打印出 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
我是 swift 和数据库的新手。我要做的就是从我的 firebase 数据库中读取。我正在使用此处提供的示例代码:https://www.firebase.com/docs/ios/guide/retrieving-data.html。 我是从我的 viewcontroller.swift 文件中调用它的 override func viewDidLoad(){}
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
我不明白为什么打印的是“(Function)”而不是我的数据。读写权限都设置为 true。我正在制作 Mac 应用程序。
您的代码示例没有提供足够的信息来说明您想做什么 - 但是,假设您想打印出 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