sar*_*rah 2 ios firebase swift google-cloud-firestore
我是编程和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)
}
}
Run Code Online (Sandbox Code Playgroud)
我getAllCitiesDataFromFirestore在CityKM课堂上使用方法来获取存储在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
]
}
}
Run Code Online (Sandbox Code Playgroud)
从我的调试区域打印
“从Firestore获取所有城市数据所需的时间:1.8787678903 s。”
有可能使其更快吗?1.8s正常吗?我在代码中是否犯了一个错误,使请求数据花费的时间太长?我希望我可以使请求时间小于一秒
我认为互联网速度不是问题,因为我可以在YouTube上打开视频而无需缓冲
这种表现听起来比我所看到的要差,但没有什么过分的。从云中加载数据只需要时间。隐藏该延迟的一种快速方法是利用Firebase的内置缓存。
当您调用时getDocuments,Firebase客户端需要在服务器上检查文档的值之后才能调用您的代码,该代码然后向用户显示该值。如前所述:无法加快代码读取速度,因此在用户看到文档之前,至少需要1.8秒的时间。
相反,如果你从数据库监听实时更新与addSnapshotListener中,火力地堡的客户端可能能够立即值从本地缓存中调用你的代码,然后再重新调用你的代码的情况下,出现了一个更新的数据服务器。
| 归档时间: |
|
| 查看次数: |
1670 次 |
| 最近记录: |