我是编程和 iOS 开发方面的新手。我正在尝试使用 Firebase 中的 Firestore 数据库制作一个应用程序。我不知道这是否正常,但是当我尝试从 firestore 数据库获取数据时,它对我来说似乎太长了。不知道是不是我写错了
这是我从 firestore 获取所有城市数据的代码
引用:
import Foundation
import FirebaseFirestore
import Firebase
enum FirestoreCollectionReference {
case users
case events
case cities
private var path : String {
switch self {
case .users : return "users"
case .events : return "events"
case .cities : return "cities"
}
}
func reference () -> CollectionReference {
return Firestore.firestore().collection(path)
}
}
我使用CityKM
类中的getAllCitiesDataFromFirestore
方法来获取存储在firestore中的城市数据
class CityKM {
var name : String
var coordinate : GeoPoint
init (name: String , coordinate: GeoPoint ) {
self.name = name
self.coordinate = coordinate
}
init (dictionary: [String:Any]) {
// this init will be used if we get data from firebase observation to construct an event object
name = dictionary["name"] as! String
coordinate = dictionary["coordinate"] as! GeoPoint
}
static func getAllCitiesDataFromFirestore (completion: @escaping ( [CityKM]? )->Void) {
// to retrieve all cities data from Firebase database by one read only, not using realtime fetching listener
let startTime = CFAbsoluteTimeGetCurrent() // to track time consumption of this method
FirestoreCollectionReference.cities.reference().getDocuments { (snapshot, error) in
if let error = error {
print("Failed to retrieve all cities data: \(error.localizedDescription)")
} else {
print("Sucessfully get all cities data from firestore")
guard let documentsSnapshot = snapshot, !documentsSnapshot.isEmpty else {
completion(nil)
return
}
let citiesDocuments = documentsSnapshot.documents
var cityArray = [CityKM]()
for document in citiesDocuments {
guard let cityName = document.data()["name"] as? String,
let cityCoordinate = document.data()["coordinate"] as? GeoPoint else {return}
let theCity = CityKM(name: cityName, coordinate: cityCoordinate)
cityArray.append(theCity)
}
completion(cityArray)
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime // to track time consumption of this method
print("Time needed to get all cities data from Firestore : \(timeElapsed) s.") // to track time consumption of this method
}
}
}
}
extension CityKM {
// MARK: - User Helper Methods
func toDictionary() -> [String:Any]{
return [
"name" : name,
"coordinate" : coordinate
]
}
}
从我的调试区域打印
"Time needed to get all cities data from Firestore : 1.8787678903 s."
是否可以加快速度? 1.8s正常吗?我的代码是否犯了一个错误,导致请求数据花费了太长时间?我希望我可以使请求时间低于一秒
我不认为网速是问题,因为我可以在 YouTube 上打开视频而无需缓冲
最佳答案
这个表现听起来比我看到的要差一些,但也没有什么过分的。从云端加载数据只是需要时间。隐藏延迟的一种快速方法是利用 Firebase 的内置缓存。
当您调用 getDocuments
时,Firebase 客户端需要先在服务器上检查文档的值,然后才能调用您的代码,然后将值显示给用户。如前所述:没有办法加快代码中的读取速度,因此用户总是需要至少 1.8 秒才能看到文档。
如果你listen for realtime updates from the database通过 addSnapshotListener
,Firebase 客户端可以立即使用本地缓存中的值调用您的代码,然后在服务器上的数据发生更新时重新调用您的代码。
关于ios - 如何更快地从 Firebase Firestore 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50289668/