一、概述
目标
在此 Codelab 中,您将使用 Swift 在 iOS 上构建一个由 Firestore 支持的餐厅推荐应用。你将学到如何:
- 从 iOS 应用程序读取数据并将数据写入 Firestore
- 实时监听 Firestore 数据的变化
- 使用 Firebase 身份验证和安全规则来保护 Firestore 数据
- 编写复杂的 Firestore 查询
先决条件
在开始此 Codelab 之前,请确保您已安装:
- Xcode 版本 13.0(或更高版本)
- CocoaPods 1.11.0(或更高版本)
2.创建Firebase控制台项目
将 Firebase 添加到项目中
- 转到Firebase 控制台。
- 选择创建新项目并将您的项目命名为“Firestore iOS Codelab”。
3.获取示例项目
下载代码
首先克隆示例项目并在项目目录中运行pod update
:
git clone https://github.com/firebase/friendlyeats-ios cd friendlyeats-ios pod update
在 Xcode 中打开FriendlyEats.xcworkspace
并运行它 (Cmd+R)。该应用程序应正确编译并在启动时立即崩溃,因为它缺少GoogleService-Info.plist
文件。我们将在下一步中更正该问题。
设置火力地堡
按照文档创建一个新的 Firestore 项目。获得项目后,从Firebase 控制台下载项目的GoogleService-Info.plist
文件并将其拖到 Xcode 项目的根目录。再次运行项目以确保应用程序配置正确并且不再在启动时崩溃。登录后,您应该会看到如下例所示的空白屏幕。如果您无法登录,请确保您已在身份验证下的 Firebase 控制台中启用电子邮件/密码登录方法。
4. 将数据写入 Firestore
在本节中,我们将向 Firestore 写入一些数据,以便我们可以填充应用 UI。这可以通过Firebase 控制台手动完成,但我们将在应用程序本身中完成,以演示基本的 Firestore 写入。
我们应用程序中的主要模型对象是餐厅。 Firestore 数据分为文档、集合和子集合。我们会将每家餐厅作为文档存储在名为restaurants
顶级集合中。如果您想了解有关 Firestore 数据模型的更多信息,请阅读文档中的文档和集合。
在我们可以将数据添加到 Firestore 之前,我们需要获得对 restaurants 集合的引用。将以下内容添加到RestaurantsTableViewController.didTapPopulateButton(_:)
方法的内部 for 循环中。
let collection = Firestore.firestore().collection("restaurants")
现在我们有了一个集合引用,我们可以写一些数据了。在我们添加的最后一行代码之后添加以下内容:
let collection = Firestore.firestore().collection("restaurants")
// ====== ADD THIS ======
let restaurant = Restaurant(
name: name,
category: category,
city: city,
price: price,
ratingCount: 0,
averageRating: 0
)
collection.addDocument(data: restaurant.dictionary)
上面的代码向 restaurants 集合添加了一个新文档。文档数据来自我们从 Restaurant 结构体中获取的字典。
我们快完成了——在我们可以将文档写入 Firestore 之前,我们需要打开 Firestore 的安全规则并描述我们数据库的哪些部分应该由哪些用户写入。现在,我们只允许经过身份验证的用户读取和写入整个数据库。这对于生产应用程序来说有点过于宽松,但在应用程序构建过程中,我们希望有足够宽松的东西,这样我们就不会在试验时经常遇到身份验证问题。在此 Codelab 结束时,我们将讨论如何强化安全规则并限制意外读写的可能性。
在 Firebase 控制台的Rules 选项卡中添加以下规则,然后单击Publish 。
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { // // WARNING: These rules are insecure! We will replace them with // more secure rules later in the codelab // allow read, write: if request.auth != null; } } }
稍后我们将详细讨论安全规则,但如果您赶时间,请查看安全规则文档。
运行应用程序并登录。然后点击左上角的“填充”按钮,这将创建一批餐厅文档,尽管您还不会在应用程序中看到它。
接下来,导航到 Firebase 控制台中的Firestore 数据选项卡。您现在应该在 restaurants 集合中看到新条目:
恭喜,您刚刚将数据从 iOS 应用程序写入 Firestore!在下一节中,您将了解如何从 Firestore 检索数据并将其显示在应用程序中。
5. 显示来自 Firestore 的数据
在本节中,您将学习如何从 Firestore 检索数据并将其显示在应用程序中。两个关键步骤是创建查询和添加快照侦听器。该侦听器将收到与查询匹配的所有现有数据的通知,并实时接收更新。
首先,让我们构建将服务于默认的、未过滤的餐馆列表的查询。看一下RestaurantsTableViewController.baseQuery()
的实现:
return Firestore.firestore().collection("restaurants").limit(to: 50)
此查询最多检索名为“restaurants”的顶级集合中的 50 家餐厅。现在我们有了一个查询,我们需要附加一个快照侦听器以将数据从 Firestore 加载到我们的应用程序中。在调用stopObserving()
之后将以下代码添加到RestaurantsTableViewController.observeQuery()
方法。
listener = query.addSnapshotListener { [unowned self] (snapshot, error) in
guard let snapshot = snapshot else {
print("Error fetching snapshot results: \(error!)")
return
}
let models = snapshot.documents.map { (document) -> Restaurant in
if let model = Restaurant(dictionary: document.data()) {
return model
} else {
// Don't use fatalError here in a real app.
fatalError("Unable to initialize type \(Restaurant.self) with dictionary \(document.data())")
}
}
self.restaurants = models
self.documents = snapshot.documents
if self.documents.count > 0 {
self.tableView.backgroundView = nil
} else {
self.tableView.backgroundView = self.backgroundView
}
self.tableView.reloadData()
}
上面的代码从 Firestore 下载集合并将其存储在本地数组中。 addSnapshotListener(_:)
调用向查询添加一个快照监听器,每当服务器上的数据发生变化时,它将更新视图控制器。我们会自动获取更新,而不必手动推送更改。请记住,此快照侦听器可以作为服务器端更改的结果随时调用,因此我们的应用程序可以处理更改很重要。
在将我们的字典映射到结构(参见Restaurant.swift
)之后,显示数据只是分配一些视图属性的问题。将以下行添加到RestaurantsTableViewController.swift
中的RestaurantTableViewCell.populate(restaurant:)
。
nameLabel.text = restaurant.name
cityLabel.text = restaurant.city
categoryLabel.text = restaurant.category
starsView.rating = Int(restaurant.averageRating.rounded())
priceLabel.text = priceString(from: restaurant.price)
这个填充方法是从表视图数据源的tableView(_:cellForRowAtIndexPath:)
方法调用的,它负责将之前的值类型集合映射到各个表视图单元格。
再次运行应用程序并验证我们之前在控制台中看到的餐厅现在在模拟器或设备上是否可见。如果您成功完成了本部分,您的应用现在可以使用 Cloud Firestore 读取和写入数据!
6.排序和过滤数据
目前我们的应用程序显示了一个餐厅列表,但用户无法根据自己的需要进行过滤。在本节中,您将使用 Firestore 的高级查询来启用过滤。
下面是一个获取所有 Dim Sum 餐厅的简单查询示例:
let filteredQuery = query.whereField("category", isEqualTo: "Dim Sum")
顾名思义, whereField(_:isEqualTo:)
方法将使我们的查询仅下载其字段满足我们设置的限制的集合成员。在这种情况下,它只会下载category
为"Dim Sum"
的餐厅。
在此应用程序中,用户可以链接多个过滤器以创建特定查询,例如“旧金山的比萨饼”或“洛杉矶按受欢迎程度订购的海鲜”。
打开RestaurantsTableViewController.swift
并将以下代码块添加到query(withCategory:city:price:sortBy:)
的中间:
if let category = category, !category.isEmpty {
filtered = filtered.whereField("category", isEqualTo: category)
}
if let city = city, !city.isEmpty {
filtered = filtered.whereField("city", isEqualTo: city)
}
if let price = price {
filtered = filtered.whereField("price", isEqualTo: price)
}
if let sortBy = sortBy, !sortBy.isEmpty {
filtered = filtered.order(by: sortBy)
}
上面的代码片段添加了多个whereField
和order
子句以基于用户输入构建单个复合查询。现在我们的查询将只返回符合用户要求的餐厅。
运行您的项目并验证您可以按价格、城市和类别进行过滤(确保准确键入类别和城市名称)。在测试时,您可能会在日志中看到如下所示的错误:
Error fetching snapshot results: Error Domain=io.grpc Code=9 "The query requires an index. You can create it here: https://console.firebase.google.com/project/project-id/database/firestore/indexes?create_composite=..." UserInfo={NSLocalizedDescription=The query requires an index. You can create it here: https://console.firebase.google.com/project/project-id/database/firestore/indexes?create_composite=...}
这是因为 Firestore 需要为大多数复合查询建立索引。要求对查询建立索引可以使 Firestore 保持快速的规模化。从错误消息中打开链接将自动在 Firebase 控制台中打开索引创建 UI,并填写正确的参数。要了解有关 Firestore 中索引的更多信息,请访问文档。
7. 在事务中写入数据
在本节中,我们将为用户添加向餐厅提交评论的功能。到目前为止,我们所有的写入都是原子的并且相对简单。如果其中任何一个出错,我们可能只是提示用户重试或自动重试。
为了给餐厅添加评级,我们需要协调多个读写操作。首先必须提交评论本身,然后餐厅的评级计数和平均评级需要更新。如果其中一个失败但另一个失败,我们将处于不一致状态,即我们数据库的一部分中的数据与另一部分中的数据不匹配。
幸运的是,Firestore 提供了事务功能,可以让我们在单个原子操作中执行多次读取和写入,从而确保我们的数据保持一致。
在RestaurantDetailViewController.reviewController(_:didSubmitFormWithReview:)
中的所有 let 声明下方添加以下代码。
let firestore = Firestore.firestore()
firestore.runTransaction({ (transaction, errorPointer) -> Any? in
// Read data from Firestore inside the transaction, so we don't accidentally
// update using stale client data. Error if we're unable to read here.
let restaurantSnapshot: DocumentSnapshot
do {
try restaurantSnapshot = transaction.getDocument(reference)
} catch let error as NSError {
errorPointer?.pointee = error
return nil
}
// Error if the restaurant data in Firestore has somehow changed or is malformed.
guard let data = restaurantSnapshot.data(),
let restaurant = Restaurant(dictionary: data) else {
let error = NSError(domain: "FireEatsErrorDomain", code: 0, userInfo: [
NSLocalizedDescriptionKey: "Unable to write to restaurant at Firestore path: \(reference.path)"
])
errorPointer?.pointee = error
return nil
}
// Update the restaurant's rating and rating count and post the new review at the
// same time.
let newAverage = (Float(restaurant.ratingCount) * restaurant.averageRating + Float(review.rating))
/ Float(restaurant.ratingCount + 1)
transaction.setData(review.dictionary, forDocument: newReviewReference)
transaction.updateData([
"numRatings": restaurant.ratingCount + 1,
"avgRating": newAverage
], forDocument: reference)
return nil
}) { (object, error) in
if let error = error {
print(error)
} else {
// Pop the review controller on success
if self.navigationController?.topViewController?.isKind(of: NewReviewViewController.self) ?? false {
self.navigationController?.popViewController(animated: true)
}
}
}
在更新块内部,我们使用事务对象进行的所有操作都将被 Firestore 视为单个原子更新。如果服务器更新失败,Firestore 会自动重试几次。这意味着我们的错误条件很可能是重复发生的单个错误,例如,如果设备完全离线或用户无权写入他们尝试写入的路径。
八、安全规则
我们应用程序的用户不应该能够读取和写入我们数据库中的每条数据。例如,每个人都应该能够看到餐厅的评级,但只有经过身份验证的用户才能发布评级。仅仅在客户端编写好的代码是不够的,我们需要在后端指定我们的数据安全模型才能完全安全。在本节中,我们将学习如何使用 Firebase 安全规则来保护我们的数据。
首先,让我们更深入地了解一下我们在 Codelab 开始时编写的安全规则。打开 Firebase 控制台并导航到Firestore 选项卡中的 Database > Rules 。
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
// Only authenticated users can read or write data
allow read, write: if request.auth != null;
}
}
}
上面规则中的request
变量是所有规则中可用的全局变量,我们添加的条件确保在允许用户执行任何操作之前对请求进行身份验证。这可以防止未经身份验证的用户使用 Firestore API 对您的数据进行未经授权的更改。这是一个好的开始,但我们可以使用 Firestore 规则来做更强大的事情。
让我们限制评论写入,以便评论的用户 ID 必须与经过身份验证的用户的 ID 匹配。这确保了用户不能互相冒充并留下欺诈性评论。用以下内容替换您的安全规则:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /restaurants/{any}/ratings/{rating} {
// Users can only write ratings with their user ID
allow read;
allow write: if request.auth != null
&& request.auth.uid == request.resource.data.userId;
}
match /restaurants/{any} {
// Only authenticated users can read or write data
allow read, write: if request.auth != null;
}
}
}
第一个匹配语句匹配属于restaurants
集合的任何文档的名为ratings
的子集合。如果评论的用户 ID 与用户的 ID 不匹配,则allow write
条件会阻止提交任何评论。第二个匹配语句允许任何经过身份验证的用户在数据库中读取和写入餐馆。
这对我们的评论非常有效,因为我们已经使用安全规则来明确声明我们之前在应用程序中写入的隐含保证——用户只能撰写他们自己的评论。如果我们要为评论添加编辑或删除功能,这组完全相同的规则也会阻止用户修改或删除其他用户的评论。但是 Firestore 规则也可以以更细化的方式使用,以限制对文档中单个字段而不是整个文档本身的写入。我们可以使用它来允许用户仅更新餐厅的评分、平均评分和评分数量,从而消除恶意用户更改餐厅名称或位置的可能性。
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /restaurants/{restaurant} {
match /ratings/{rating} {
allow read: if request.auth != null;
allow write: if request.auth != null
&& request.auth.uid == request.resource.data.userId;
}
allow read: if request.auth != null;
allow create: if request.auth != null;
allow update: if request.auth != null
&& request.resource.data.name == resource.data.name
&& request.resource.data.city == resource.data.city
&& request.resource.data.price == resource.data.price
&& request.resource.data.category == resource.data.category;
}
}
}
在这里,我们将写入权限拆分为创建和更新,这样我们就可以更具体地说明应该允许哪些操作。任何用户都可以将餐厅写入数据库,保留我们在 Codelab 开始时创建的 Populate 按钮的功能,但餐厅一旦写入,其名称、位置、价格和类别就无法更改。更具体地说,最后一条规则要求任何餐厅更新操作保持数据库中已有字段的相同名称、城市、价格和类别。
要详细了解您可以使用安全规则做什么,请查看文档。
9.结论
在此 Codelab 中,您学习了如何使用 Firestore 进行基本和高级读写,以及如何使用安全规则保护数据访问。您可以在codelab-complete
分支上找到完整的解决方案。
要了解有关 Firestore 的更多信息,请访问以下资源: