Cloud Firestore iOS 代码实验室

1. 概述

目标

在此 Codelab 中,您将使用 Swift 在 iOS 上构建一个由 Firestore 支持的餐厅推荐应用。你将学到如何:

  1. 从 iOS 应用读取数据并将其写入 Firestore
  2. 实时监听 Firestore 数据的变化
  3. 使用 Firebase 身份验证和安全规则来保护 Firestore 数据
  4. 编写复杂的 Firestore 查询

先决条件

在开始此 Codelab 之前,请确保您已安装:

  • Xcode 版本 14.0(或更高版本)
  • CocoaPods 1.12.0(或更高版本)

2.创建Firebase控制台项目

将 Firebase 添加到项目中

  1. 转到Firebase 控制台
  2. 选择“创建新项目”并将您的项目命名为“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文件。我们将在下一步中纠正该问题。

设置 Firebase

按照文档创建新的 Firestore 项目。获得项目后,从Firebase 控制台下载项目的GoogleService-Info.plist文件并将其拖到 Xcode 项目的根目录。再次运行项目以确保应用程序配置正确并且在启动时不再崩溃。登录后,您应该会看到一个空白屏幕,如下例所示。如果您无法登录,请确保您已在 Firebase 控制台的“身份验证”下启用了电子邮件/密码登录方法。

d5225270159c040b.png

4. 将数据写入Firestore

在本部分中,我们将向 Firestore 写入一些数据,以便填充应用程序 UI。这可以通过Firebase 控制台手动完成,但我们将在应用程序本身中执行此操作以演示基本的 Firestore 写入。

我们应用程序中的主要模型对象是一家餐厅。 Firestore 数据分为文档、集合和子集合。我们将把每家餐厅作为文档存储在名为restaurants顶级集合中。如果您想了解有关 Firestore 数据模型的更多信息,请阅读文档中有关文档和集合的信息。

在将数据添加到 Firestore 之前,我们需要获取对餐馆集合的引用。将以下内容添加到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)

上面的代码向餐厅集合添加了一个新文档。文档数据来自字典,我们从 Restaurant 结构中获取该字典。

我们快要完成了——在将文档写入 Firestore 之前,我们需要打开 Firestore 的安全规则并描述数据库的哪些部分应该由哪些用户写入。目前,我们只允许经过身份验证的用户读取和写入整个数据库。对于生产应用程序来说,这有点过于宽松,但在应用程序构建过程中,我们希望事情足够宽松,这样我们就不会在实验时不断遇到身份验证问题。在本 Codelab 的最后,我们将讨论如何强化安全规则并限制意外读写的可能性。

在 Firebase 控制台的“规则”选项卡中添加以下规则,然后单击“发布”

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 数据选项卡。您现在应该在餐馆集合中看到新条目:

屏幕截图 2017-07-06 12.45.38 PM.png

恭喜,您刚刚从 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 读取和写入数据!

391c0259bf05ac25.png

6. 数据排序和过滤

目前我们的应用程序显示餐厅列表,但用户无法根据自己的需求进行过滤。在本部分中,您将使用 Firestore 的高级查询来启用过滤。

以下是获取所有点心餐厅的简单查询示例:

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)
}

上面的代码片段添加了多个whereFieldorder子句,以根据用户输入构建单个复合查询。现在我们的查询将仅返回符合用户要求的餐厅。

运行您的项目并验证您可以按价格、城市和类别进行过滤(确保准确输入类别和城市名称)。在测试时,您可能会在日志中看到如下错误:

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 会自动重试几次。这意味着我们的错误条件很可能是重复发生的单个错误,例如,如果设备完全离线或用户无权写入他们尝试写入的路径。

8. 安全规则

我们应用程序的用户不应该能够读取和写入数据库中的每条数据。例如,每个人都应该能够看到餐厅的评级,但只有经过身份验证的用户才可以发布评级。在客户端编写好的代码是不够的,我们需要在后端指定我们的数据安全模型以确保完全安全。在本部分中,我们将学习如何使用 Firebase 安全规则来保护我们的数据。

首先,让我们更深入地了解一下我们在 Codelab 开始时编写的安全规则。打开 Firebase 控制台并导航到Firestore 选项卡中的数据库 > 规则

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 开始时创建的填充按钮的功能,但是一旦写入餐馆,其名称、位置、价格和类别就无法更改。更具体地说,最后一条规则要求任何餐厅更新操作都保持数据库中现有字段的名称、城市、价格和类别相同。

要详细了解如何使用安全规则,请查看文档

9. 结论

在此 Codelab 中,您学习了如何使用 Firestore 进行基本和高级读写,以及如何使用安全规则保护数据访问。您可以在codelab-complete分支上找到完整的解决方案。

要了解有关 Firestore 的更多信息,请访问以下资源: