gpt4 book ai didi

swift - 从 Firebase 读取数据时发生类型转换错误

转载 作者:行者123 更新时间:2023-11-30 10:34:41 25 4
gpt4 key购买 nike

我正在使用mapkit制作一个应用程序,当我尝试从firebase获取用户位置时,它会导致这三行出现错误

let dict = recipeSnap.value as! [String:Double?]

let latitude = dict["latitude"] as? Double?

let longitude = dict["longitude"] as? Double?.

我尝试用字符串替换 double ,但发生了新错误,然后我尝试用 AnyObject 替换它,它有效,但数据类似于可选(37.785834)。当我使用 AnyObject 数据做其他事情时,它总是会导致错误。

这是我的代码

@objc func updateTimer(){

print("Update location")
let location = locman.location!.coordinate
lat = String(location.latitude)
long = String(location.longitude)
print(lat)
print(long)
let ref = Database.database().reference()
ref.child("location/User1/longitude").setValue(long)
ref.child("location/User1/latitude").setValue(lat)
ref.child("location").observeSingleEvent(of: .value) { (snapshot) in
self.usern = snapshot.childrenCount
for snap in snapshot.children{
let aSnap = snap as! DataSnapshot
let dict = aSnap.value as! [String:Double?]
let latitude = dict["latitude"] as? Double?
let longitude = dict["longitude"] as? Double?
print(dict)
print(latitude)
print(longitude)

let point = MKPointAnnotation()
point.title = "user"
//point.coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(latitude), longitude: CLLocationDegrees(longitude))
self.mapView.addAnnotation(point)
}
}
}

这是我的错误

Could not cast value of type 'Swift._NSContiguousString' (0x1032681f8) to 'NSNumber' (0x1b7a1abf0). 2019-10-10 20:24:05. mapkitMap[1468:709956] Could not cast value of type 'Swift._NSContiguousString' (0x1032681f8) to 'NSNumber' (0x1b7a1abf0). Optional(37.785834)

当我尝试用字符串替换 Double 时,出现新错误

Could not cast value of type '__NSCFNumber' (0x1b7a0e0e0) to 'NSString' (0x1b7a1aad8). 2019-10-10 20:20:32.1 mapkitMap[1465:708355] Could not cast value of type '__NSCFNumber' (0x1b7a0e0e0) to 'NSString' (0x1b7a1aad8).

最佳答案

您似乎将一些纬度经度存储为字符串值,

lat = String(location.latitude)
long = String(location.longitude)

因此您不能简单地从数据库中将它们作为数字检索。您需要从数据库中将它们作为字符串读取,然后解析它们的数值。

类似于:

  let aSnap = snap as! DataSnapshot  
let latitude = Double(snap.childSnapshot(forPath: "latitude").value)
let longitude = Double(snap.childSnapshot(forPath: "longitude").value)

关于swift - 从 Firebase 读取数据时发生类型转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58323315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com