Eli*_*iko 1 ios firebase swift firebase-realtime-database
在转到Swift 3 之前,这是我的代码:
ref.observeEventType(.ChildAdded, withBlock: { snapshot in
let currentData = snapshot.value!.objectForKey("Dogs")
if currentData != nil {
let mylat = (currentData!["latitude"])! as! [String]
let mylat2 = Double((mylat[0]))
let mylon = (currentData!["longitude"])! as! [String]
let mylon2 = Double((mylon[0]))
let userid = (currentData!["User"])! as! [String]
let userid2 = userid[0]
let otherloc = CLLocation(latitude: mylat2!, longitude: mylon2!)
self.distanceBetweenTwoLocations(self.currentLocation, destination: otherloc, userid: userid2)
}
})
Run Code Online (Sandbox Code Playgroud)
这是我移动到Swift 3 后的代码:
ref.observe(.childAdded, with: { snapshot in
let currentData = (snapshot.value! as AnyObject).object("Dogs")
if currentData != nil {
let mylat = (currentData!["latitude"])! as! [String]
let mylat2 = Double((mylat[0]))
let mylon = (currentData!["longitude"])! as! [String]
let mylon2 = Double((mylon[0]))
let userid = (currentData!["User"])! as! [String]
let userid2 = userid[0]
let otherloc = CLLocation(latitude: mylat2!, longitude: mylon2!)
self.distanceBetweenTwoLocations(self.currentLocation, destination: otherloc, userid: userid2)
}
})
Run Code Online (Sandbox Code Playgroud)
然后我在第二行收到错误:
不能调用非函数类型的值'Any?!'
我唯一尝试的是将第二行更改为此代码:
snapshot.value as! [String:AnyObject]
Run Code Online (Sandbox Code Playgroud)
但它不对,没有包含"狗",它给了我一个警告,distanceBetweenTwoLocations
代码从未使用过.
看到的问题是,当您实例化并初始化变量时,您告诉它它将接收的值将是该类型为的快照中value
名为Dogs
present 的对象AnyObject
.
但是snapshot.value
类型为Dictionary ie [String:AnyObject]
,NSDictionary
..
Dogs
您检索的节点类型为Dictionary或Array.
基本上,您应该避免将值存储在AnyObject类型的变量中
试试这个:-
FIRDatabase.database().reference().child("Posts").child("post1").observe(.childAdded, with: { snapshot in
if let currentData = (snapshot.value! as! NSDictionary).object(forKey: "Dogs") as? [String:AnyObject]{
let mylat = (currentData["latitude"])! as! [String]
let mylat2 = Double((mylat[0]))
let mylon = (currentData["longitude"])! as! [String]
let mylon2 = Double((mylon[0]))
let userid = (currentData["User"])! as! [String]
let userid2 = userid[0]
let otherloc = CLLocation(latitude: mylat2!, longitude: mylon2!)
self.distanceBetweenTwoLocations(self.currentLocation, destination: otherloc, userid: userid2)
}
})
Run Code Online (Sandbox Code Playgroud)
PS: -看到你的JSON结构你可能想把它转换成字典而不是数组
归档时间: |
|
查看次数: |
4737 次 |
最近记录: |