firebase ios_适用于Android和iOS的Firebase实时数据库登录教程

firebase ios

Mobile apps need a backend. They store settings & data, high scores, check licenses and generate statistics. All these use cases have one thing in common: they use a central database.

移动应用程序需要后端。 他们存储设置和数据,高分,检查许可证并生成统计信息。 所有这些用例都有一个共同点:它们使用中央数据库。

Coding a full-blown backend takes a lot of time. Think about end-to-end security, communication interfaces and database structure. When you then get to details like concurrent access, it gets tricky.

编码一个完整的后端需要很多时间。 考虑端到端的安全性,通信接口和数据库结构。 然后,当您获得诸如并发访问之类的详细信息时,就会很棘手。

Luckily, Google Firebase takes care of all these issues for you. It’s a ready-to-use cloud-hosted database with full authentication support. In contrast to a traditional SQL database, Google Firebase stores JSON data sets (-> NoSQL). This gives you more flexibility in your data structure.

幸运的是, Google Firebase会为您解决所有这些问题。 这是一个具有完整身份验证支持的即用型云托管数据库。 与传统SQL数据库相比,Google Firebase存储JSON数据集(-> NoSQL )。 这为您的数据结构提供了更大的灵活性。

On top of that, you can subscribe to real-time data changes. You’ll get notified about updates made to the data, for example by other users. The service does offer a simple REST API. But the most efficient communication is a publish & subscribe model via websockets.

最重要的是,您可以订阅实时数据更改。 您将收到有关数据更新的通知,例如其他用户。 该服务确实提供了简单的REST API 。 但是最有效的通信是通过websockets的发布和订阅模型。

That sounds complicated? Google offers a separate SDK for each platform. With Felgo & Qt, you don’t need to worry about platform differences. Felgo includes a cross-platform Google Firebase Realtime Database plugin. The same QML / JavaScript-based API works for both Android & iOS.

听起来复杂吗? Google为每个平台提供了单独的SDK。 使用Felgo&Qt,您无需担心平台差异。 Felgo包含一个跨平台的Google Firebase实时数据库插件 。 相同的基于QML / JavaScript的API适用于Android和iOS。

If you need help with that, consult or outsource your app development with Felgo.

如果您需要帮助,请向Felgo咨询或外包您的应用程序开发 。

入门 (Getting Started)

In this Firebase tutorial, you’ll complete the full journey from start to end. You start with a project template of Qt Creator. Next, you’ll set up the Firebase service in the cloud. Another important task is user authentication. Most impressive: live database updates from & to your cross-platform app.

在此Firebase教程中,您将完成从头到尾的整个旅程。 您将从Qt Creator的项目模板开始。 接下来,您将在云中设置Firebase服务。 另一个重要任务是用户身份验证。 最令人印象深刻的是:从&跨平台应用实时更新数据库。

The scenario is a simple shopping list. It’s a generic app that includes everything most apps need. Authentication, plus adding, updating and deleting items. Once you understand the concepts, it’s easy to adapt them to your own scenario.

该方案是一个简单的购物清单。 这是一个通用应用程序,其中包含大多数应用程序需要的所有内容。 身份验证,以及添加,更新和删除项目。 一旦理解了这些概念,就很容易将它们适应您自己的方案。

If you’re impatient, skip right to the final project source code on GitHub.

如果您不耐烦,请直接跳至GitHub上的最终项目源代码。

在YouTube上观看本教程 (Watch this Tutorial on YouTube)

You can also watch the video version of this tutorial on YouTube. It is very much in-depth and covers every single step of the process.

您也可以在YouTube上观看本教程的视频版本。 它非常深入,涵盖了过程的每个步骤。

您的Cloud Backend的主从UI (Master-Detail UI for your Cloud Backend)

Curious to dive right into the cloud database? Well, you will need your “app package name” for Android and the “iOS bundle ID” when setting up Firebase.

是否想直接进入云数据库? 好了,设置Firebase时,您将需要Android的“应用程序包名称”和“ iOS软件包ID”。

Thus, start with the app and make your life easier. Open Qt Creator and create a new project. Use the “Felgo Apps” > “Master-Detail Application”. This gives you great boilerplate code for any list-type app.

因此,从该应用程序开始,使您的生活更轻松。 打开Qt Creator并创建一个新项目。 使用“ Felgo应用程序”>“主从应用程序”。 这为您提供了任何列表类型应用程序的出色样板代码。

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第1张图片

In step 2, choose the kits for the target platforms: Android and/or iOS.

在步骤2中,选择目标平台的工具包:Android和/或iOS。

Take special note of the “Felgo Project Properties” page (step 3). Here, you define the app identifier, which you will also need for the Firebase setup. In this case, choose com.vplay.ShoppingList.

特别注意“ Felgo项目属性”页面(步骤3)。 在这里,您可以定义应用程序标识符,Firebase设置也需要该标识符。 在这种情况下,请选择com.vplay.ShoppingList

Google offers different Firebase samples for individual platforms & tools. With Felgo, you run the same code across Android & iOS. Activate the “Google Firebase” plugin. It includes ready-made cross-platform code to interact with the Google cloud!

Google针对各个平台和工具提供了不同的Firebase示例。 使用Felgo,您可以在Android和iOS上运行相同的代码。 激活“ Google Firebase”插件。 它包括现成的跨平台代码,可与Google云进行交互!

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第2张图片

在Android和iOS上进行实时测试 (Live Testing on Android & iOS)

If you target both Android and iOS, you’ll want to test your app on both platforms. Felgo Live immediately deploys and executes any code changes on any connected phone. You can even connect and test on iOS phones while developing on Windows. You save an incredible amount of time: no more re-building, deploying and testing.

如果您同时定位Android和iOS,则需要在两个平台上测试您的应用。 Felgo Live立即在任何连接的电话上部署并执行任何代码更改。 在Windows上进行开发时,您甚至可以在iOS手机上进行连接和测试。 您节省了不可思议的时间:无需重新构建,部署和测试。

To get started, download the Felgo Live app from the app store: Android / iOS. Next, make sure your development computer and the phone are on the same local network. Start the Felgo Live app on your phone and connect it to your Live Server. If your Live Server is not running yet, click on “Live Run” in Qt Creator, to start developing with live code reloading!

首先,请从以下应用商店中下载Felgo Live应用: Android / iOS 。 接下来,确保您的开发计算机和电话在同一本地网络上。 在手机上启动Felgo Live应用程序,然后将其连接到Live Server。 如果您的Live Server尚未运行,请在Qt Creator中单击“ Live Run”,开始使用实时代码重新加载进行开发!

Felgo插件许可证 (Felgo Plugin License)

Your app currently shows a watermark that you’re running a trial of the Firebase plugin. That’s fine for your first testing steps! To get rid of the trial watermark and the license reminders, you need the Felgo Indie license. If you do not have an Indie license, you can continue using the Firebase plugin in trial mode, without generating a license key.

您的应用当前显示一个水印,表明您正在试用Firebase插件。 这对您的第一个测试步骤很好! 要摆脱试用水印和许可证提醒,您需要Felgo Indie许可证。 如果您没有独立许可证,则可以在试用模式下继续使用Firebase插件,而无需生成许可证密钥。

Authorization works through a license key for your app. Go to https://felgo.com/upgradeLicense. Select the “Google Firebase” plugin. Next, click the green “Generate License Key” button at the bottom of the page.

授权通过您的应用程序的许可证密钥进行。 前往https://felgo.com/upgradeLicense 。 选择“ Google Firebase”插件。 接下来,单击页面底部的绿色“ Generate License Key”按钮。

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第3张图片

Next, enter your app identifier (e.g., “com.vplay.ShoppingList”). The suggested version “1” is correct — it’s the default in every new project.

接下来,输入您的应用标识符(例如,“ com.vplay.ShoppingList”)。 建议的版本“ 1”是正确的-这是每个新项目中的默认版本。

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第4张图片

Copy the new license key to your code, add it to the licenseKey property in your Main.qml file. The watermark disappears. This video shows the original Master-Detail sample app. When inserting the license key to the code, the app instantly reloads — without the watermark. Afterwards, you see a brief demo of the initial app functionality.

将新的许可证密钥复制到您的代码中,然后将其添加到Main.qml文件中的licenseKey属性中。 水印消失。 该视频显示了原始的Master-Detail示例应用程序。 将许可证密钥插入代码时,该应用程序会立即重新加载-不带水印。 之后,您将看到有关初始应用程序功能的简短演示。

创建Firebase项目 (Create the Firebase Project)

Congratulations, your master-detail app is running on the phone! Now, it’s time to create the Google Firebase Realtime database. This serves as complete lightweight backend for the shopping list example app.

恭喜,您的主从应用程序正在手机上运行! 现在,该创建Google Firebase Realtime数据库了。 这可作为购物清单示例应用程序的完整轻量级后端。

To create a Firebase account, go to the Firebase homepage. Login with your Google Account to see the empty console. The project you create runs great with the free account. You don’t need to worry about payments.

要创建Firebase帐户,请转到Firebase主页 。 使用您的Google帐户登录以查看空白控制台。 您创建的项目使用免费帐户运行良好。 您无需担心付款。

First, click on “Add project”.

首先,单击“添加项目”。

Give your project a name to recognize it in your console: “ShoppingList”. The “Project ID” is auto-generated with a number, as it needs to be globally unique. You can customize the ID if you like. Note that your users will never see this ID, though — so don’t spend too much time here.

为您的项目命名,以便在控制台中识别它:“ ShoppingList”。 “项目ID”会自动生成一个数字,因为它必须是全局唯一的。 您可以根据需要自定义ID。 请注意,尽管如此,您的用户将永远不会看到此ID,因此请不要在这里花费太多时间。

Image for post

Click on “CREATE PROJECT”. In a few seconds, the project dashboard greets you with the overview:

点击“创建项目”。 几秒钟后,项目仪表板将向您介绍概述:

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第5张图片

将您的应用程序连接到Firebase (Connect Your App to Firebase)

Your shopping list app stores the items in the cloud. Grant your app access to the Firebase project. Click on the big circle for your target platform: iOS or Android.

您的购物清单应用程序将项目存储在云中。 授予您的应用对Firebase项目的访问权限。 单击目标平台的大圆圈:iOS或Android。

Enter the package name again. The optional “app nickname” is only for internal use inside your dashboard.

再次输入软件包名称。 可选的“应用程序昵称”仅在仪表板内部仅供内部使用。

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第6张图片

The Firebase wizard now prompts to download the config file. Download this file and store it somewhere on your computer.

Firebase向导现在提示下载配置文件。 下载此文件并将其存储在计算机上的某个位置。

The major parts of the config file look like this. They contain all the information you need to connect your app to Firebase.

配置文件的主要部分如下所示。 它们包含将应用程序连接到Firebase所需的所有信息。

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

For your Felgo project, you could use this config file. But it’s easier to copy the API keys to the plugin config, as you will see below. So, skip steps 3 + 4 of the Firebase wizard.

对于您的Felgo项目,您可以使用此配置文件。 但是将API密钥复制到插件配置会更容易,如下所示。 因此,请跳过Firebase向导的步骤3 + 4。

In Qt Creator’s “Projects” view, right-click the “qml” folder. Select “Add new…”. Choose the “Felgo Apps” -> “Item” template.

在Qt Creator的“项目”视图中,右键单击“ qml”文件夹。 选择“添加新…”。 选择“ Felgo应用程序”->“项目”模板。

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第7张图片

In the following “Item details” dialog, enter:

在以下“项目详细信息”对话框中,输入:

  • File name: DataModel

    档案名称: DataModel

  • Path: create a new sub-folder in your project’s qml folder, called “model”

    路径:在项目的qml文件夹中创建一个新的子文件夹,称为“模型”

The generated file is almost empty. Change the default generated ID from “item” to “dataModel”. As you are using the Firebase plugin, add the following line to the import section at the beginning of the file:

生成的文件几乎为空。 将默认生成的ID从“ item”更改为“ dataModel”。 在使用Firebase插件时,将以下行添加到文件开头的import部分:

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

The FirebaseConfig QML element encapsulates all connection settings — for both Android and iOS. Add it to your item. Your data model now looks like this:

FirebaseConfig QML元素封装了所有连接设置-适用于Android和iOS。 将其添加到您的项目。 现在,您的数据模型如下所示:

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

Firebase数据库设置 (Firebase Database Setup)

Your app will store a list of items in the database. Firebase is a JSON-based NoSQL database. What does it do?

您的应用程序将在数据库中存储项目列表。 Firebase是基于JSON的NoSQL数据库 。 它有什么作用?

This is what your database will look like:

这是您的数据库的外观:

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第8张图片

The database is a tree of items. Each can have children and any structure. That makes the database much more flexible than tables in traditional SQL.

数据库是一棵项目树。 每个人都可以有孩子和任何结构。 这使得数据库比传统SQL中的表更加灵活。

Some of the structure is pre-defined by Firebase; some is coming from your app. A quick overview, before you dive in:

一些结构是由Firebase预先定义的; 有些来自您的应用。 在您深入之前,请快速浏览一下:

  1. shoppinglist-vplay: the root node of the entire database (shown in yellow).

    shoppinglist-vplay:整个数据库的根节点 (以黄色显示)。

  2. users: each user is going to have a private shopping list. After all, you don’t want to buy items that a stranger added, right? Thus, the next node is “users”. It contains a list of user UIDs. The database itself doesn’t store any further information about the user’s identity. You can look this up in the “Authentication” section of your Firebase project dashboard:

    用户:每个用户都有一个私人购物清单。 毕竟,您不想购买陌生人添加的物品,对吗? 因此,下一个节点是“用户”。 它包含用户UID的列表。 数据库本身不存储有关用户身份的任何进一步信息。 您可以在Firebase项目仪表板的“身份验证”部分中进行查找:

  1. shoppinglist-user: the root node of the individual shopping list. This is what a logged-in user sees. It contains several items, one for each item to buy. Here, it’s currently milk and apples.

    shoppinglist-user:单个购物清单的根节点。 这是登录用户所看到的。 它包含几个项目,每个项目要购买一个。 在这里,目前是牛奶和苹果。

创建云数据库 (Create the Cloud Database)

In your browser, return to the Firebase dashboard. Select “Database” on the left. Next, click on “Get Started” in the “Realtime Database” block. The Cloud Firestore is currently still in beta. That’s why it’s not recommended for production use yet. We will take a closer look in a future tutorial.

在浏览器中,返回到Firebase仪表板。 选择左侧的“数据库”。 接下来,在“实时数据库”块中单击“入门”。 Cloud Firestore目前仍处于测试阶段。 这就是为什么不建议将其用于生产的原因。 我们将在以后的教程中仔细研究。

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第9张图片

Next up is the “Security rules for Realtime Database” dialog. It’s a good idea to start with proper authentication right away, instead of plugging it in later.

接下来是“实时数据库的安全规则”对话框。 最好立即进行正确的身份验证,而不是稍后再插入。

Firebase身份验证 (Firebase Authentication)

Your app needs to recognize, differentiate and securely authorize users. The Firebase Authentication service makes this easy. It supports multiple authorization providers: Facebook, Google Account, Twitter, GitHub and even a phone-based user authentication per SMS.

您的应用程序需要识别,区分和安全地授权用户。 Firebase身份验证服务使此操作变得容易。 它支持多个授权提供者:Facebook,Google帐户,Twitter,GitHub,甚至每个SMS都基于电话的用户身份验证。

Firebase even lets you use “anonymous” authentication. This means the user does not have to do any authentication step in order to use the Firebase Database.

Firebase甚至允许您使用“匿名”身份验证。 这意味着用户无需执行任何身份验证步骤即可使用Firebase数据库。

To get started, we will use the Email / Password variant. Firebase takes care of managing users and even supports sending password reset emails.

首先,我们将使用“电子邮件/密码”变体。 Firebase负责管理用户,甚至支持发送密码重置电子邮件。

To activate it, go to the Authentication section (1) of your Firebase dashboard.

要激活它,请转到Firebase仪表板的“身份验证”部分(1)。

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第10张图片

Next, choose “Sign-In Method” (2). Click on “Email/Password” (3) to expand this section. Enable it (4) and save the changes (5). In the “Templates” section, you could further customize the behavior. E.g., a custom confirmation email text when a user signs up.

接下来,选择“登录方法”(2)。 单击“电子邮件/密码”(3)展开此部分。 启用它(4)并保存更改(5)。 在“模板”部分中,您可以进一步自定义行为。 例如,用户注册时的自定义确认电子邮件文本。

从您的客户端应用程序登录Firebase:体系结构 (Firebase Login from Your Client App: Architecture)

Felgo simplifies the authentication process. The engine includes a predefined item FirebaseAuth that handles the cloud communication.

Felgo简化了身份验证过程。 该引擎包括一个预定义项FirebaseAuth ,用于处理云通信。

The app architecture is clear:

该应用程序架构很明确:

  • The App is the main QML item that owns all the other items and ensures they communicate with each other

    应用程序是拥有所有其他项目并确保它们彼此通信的主要QML项目

  • DataModel is a direct child of the App. It is a layer that handles the authentication and shopping items (your data). It abstracts the Google Firebase. The rest of your application does not need to worry about the backend or any cloud communication.

    DataModel是该应用程序的直接子代。 它是处理身份验证和购物项目(您的数据)的层。 它抽象了Google Firebase。 您的应用程序的其余部分无需担心后端或任何云通信。

    Its

    它的

    onLoggedIn slot triggers navigating from the LoginPage to the ShoppingListPage.

    onLoggedIn插槽触发从LoginPage导航到ShoppingListPage

  • FirebaseAuth is an item provided by Felgo. It communicates with the Firebase cloud. It provides convenient signals and slots. These integrate the relevant events into your app.

    FirebaseAuth是Felgo提供的一项。 它与Firebase云通信。 它提供了方便的信号和插槽。 这些将相关事件集成到您的应用程序中。

  • FirebaseConfig is what we’ve already created. It contains basic settings, like the API key, configuration, …

    FirebaseConfig是我们已经创建的。 它包含基本设置,例如API密钥,配置等。

  • NavigationStack handles all the visible pages.

    NavigationStack处理所有可见页面。

  • LoginPage is initially visible. It contains the user interface to enter username and password. Plus, you can trigger new user registrations for the Firebase backend.

    LoginPage最初是可见的。 它包含用于输入用户名和密码的用户界面。 另外,您可以触发Firebase后端的新用户注册。

    Its

    它的

    onLogin slot executes when the user taps the button to login / register.

    当用户点击按钮登录/注册时, onLogin插槽执行。

  • ShoppingListPage shows all the shopping items, which you’ll retrieve from the Firebase database. It is only visible after successful authentication.

    ShoppingListPage显示所有购物项目,您将从Firebase数据库中检索这些项目。 仅在成功认证后可见。

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第11张图片

Firebase身份验证:来自云的回调 (Firebase Authentication: Callbacks from the Cloud)

You start by adding the FirebaseAuth item to your DataModel. It is simple to use: assign an ID and give it a reference to the config item you created before. Also, add two signals (“loggedIn”, “loggedOut”) to your DataModel. They inform the app about the user’s login status.

首先,将FirebaseAuth项目添加到您的DataModel中。 它很容易使用:分配一个ID并为其提供对您之前创建的配置项的引用。 此外,向您的DataModel添加两个信号(“ loggedIn”,“ loggedOut”)。 它们会将用户的登录状态通知应用。

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

FirebaseAuth offers three important slots for reacting to cloud responses:

FirebaseAuth提供了三个用于响应云响应的重要插槽:

  1. onLoggedIn: fired after the loginUser request has finished. This is a good place for you to check if there was an issue with the login.

    onLoggedIn: loginUser请求完成后触发。 这是您检查登录是否有问题的好地方。

  2. onUserRegistered: like the login, but for a finished registerUser request.

    onUserRegistered:类似于登录名,但用于完成的registerUser请求。

  3. onAuthenticationChanged: the most important status change: is the user logged in? With this generic slot, your app is flexible no matter how the user logged in. All that matters is if he is logged in at the end. In that case, our DataModel emits the loggedIn signal to let the app switch to the main data model page.

    onAuthenticationChanged:最重要的状态更改:用户是否登录? 有了这个通用槽,你的应用是灵活的,无论用户如何登录,所有重要的是,如果他在年底记录下来。 在这种情况下,我们的DataModel会发出loggingIn信号,以使应用切换到主数据模型页面。

Firebase:触发登录,用户注册和注销 (Firebase: Triggering Login, User Registration and Logout)

Now, your app already handles the status change responses coming from Firebase. But, you still need to trigger the login! The FirebaseAuth item includes convenient methods for triggering authentication tasks.

现在,您的应用程序已经可以处理来自Firebase的状态更改响应。 但是,您仍然需要触发登录! FirebaseAuth项包括触发身份验证任务的便捷方法。

Your DataModel.qml encapsulates the communication with Firebase. So, you include simple methods that forward the requests to Firebase.

您的DataModel.qml封装了与Firebase的通信。 因此,您包括了将请求转发到Firebase的简单方法。

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

You might wonder why you should do this. After all, the new methods are an exact replica of the existing. Once you expand your app, you might want to surround these calls with extra checks. E.g., you could test if the email address is valid. So, it’s a good idea to think of a good architecture right from the start.

您可能想知道为什么要这样做。 毕竟,新方法是现有方法的精确副本。 扩展应用程序后,您可能需要对这些调用进行额外的检查。 例如,您可以测试电子邮件地址是否有效。 因此,从一开始就考虑好的架构是一个好主意。

应用中的Firebase登录流程 (Firebase Login Flow in the App)

The example app already includes two sample pages for Firebase, which we will not use however. They are a concise essence of what you can do with Firebase. In our sample, we use Firebase as part of the complete app architecture.

该示例应用程序已经包含两个Firebase示例页面,但是我们将不使用它们。 它们是您可以使用Firebase进行的简洁的本质。 在我们的示例中,我们将Firebase用作完整应用程序体系结构的一部分。

Create a new page: LoginPage.qml. It’s will be a simple page with 2 text boxes and a button. A checkbox switches between login and new user registration. Copy the source code from the GitHub sample into your new page.

创建一个新页面:LoginPage.qml。 这将是一个简单的页面,带有2个文本框和一个按钮。 复选框在登录和新用户注册之间切换。 将源代码从GitHub示例复制到您的新页面中。

Important for the concept is that the page emits a signal once the user taps the button: “login(bool isRegister, string email, string password)”. The parameters include everything Firebase needs to perform the login.

这个概念的重要意义在于,一旦用户点击按钮,页面就会发出信号:“登录(bool isRegister,字符串电子邮件,字符串密码)”。 参数包括Firebase执行登录所需的所有内容。

Main.qml wires this signal to your DataModel. This connection establishes the link from the UI to the Firebase cloud. Replace the current contents of Main.qml with:

Main.qml将此信号连接到您的DataModel。 此连接建立从UI到Firebase云的链接。 将Main.qml的当前内容替换为:

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

In the code snippet above, you see that the App also owns the DataModel item with id “dataModel”. The “App” item connects your app’s components. Here, you establish a direct connection: LoginPage’s “onLogin”-slot -> methods of the DataModel (registerUser / loginUser).

在上面的代码片段中,您看到该应用程序还拥有ID为“ dataModel”的DataModel项。 “应用程序”项连接您应用程序的组件。 在这里,您可以建立直接连接:LoginPage的“ onLogin” -slot-> DataModel的方法(registerUser / loginUser)。

Once the login process completes, the “onLoggedIn” slot within the DataModel pushes the “shoppingListPage” to the navigation stack. Remember: that’s the ID of the MasterPage from the template.

登录过程完成后,DataModel中的“ onLoggedIn”插槽会将“ shoppingListPage”推入导航堆栈。 请记住:这是模板中MasterPage的ID。

With this approach, navigating back in the Android / iPhone-UI pops the page. This automatically triggers the logout process in Firebase. Your app also returns to the previous page on the navigation stack — the LoginPage.

使用这种方法,在Android / iPhone-UI中导航回去会弹出页面。 这会自动触发Firebase中的注销过程。 您的应用程序还会返回到导航堆栈的上一页-LoginPage。

Test your app! You can already register a new user in Google Firebase and log in:

测试您的应用! 您已经可以在Google Firebase中注册新用户并登录:

Firebase实时数据库和定价 (Firebase Realtime Database & Pricing)

The Firebase Realtime Database is a NoSQL DB. It’s efficient and low-latency, and especially targeted towards mobile clients.

Firebase实时数据库是NoSQL数据库。 它高效且低延迟,特别针对移动客户端。

The Realtime Database stores all data in a JSON tree. Unlike a SQL database, there are no tables and rows. That makes Firebase efficient for simple and rather flat data. It’s the ideal target for many apps, like our shopping list example.

实时数据库将所有数据存储在JSON树中。 与SQL数据库不同,没有表和行。 这使得Firebase 对于简单且相当平坦的数据有效 。 这是许多应用程序的理想目标,例如我们的购物清单示例。

What about pricing? You get charged for bandwidth and storage. The free “Spark Plan” already grants you 100 simultaneous connections, 1 GB of data storage and 10 GB / month data transfer. Upgrades to the “Flame Plan” and the “Blaze Plan” give you even more data allowance. Google has a good comparison table, highlighting the differences between different Firebase plans.

定价呢? 您需要为带宽和存储付费。 免费的“火花计划”已经为您提供100个同时连接,1 GB的数据存储和10 GB /月的数据传输。 升级到“火焰计划”和“大火计划”可为您提供更多数据余量。 Google有一个很好的比较表 ,突出显示了不同Firebase计划之间的差异。

Firebase数据库结构和实时更新 (Firebase Database Structure & Live Updates)

The following video shows a screen recording of what’s happening behind the scenes:

以下视频显示了幕后发生的事情的屏幕录像:

  1. Left: A new user registers. You see his identifier (the email address). It’s linked to a unique UID (“lC27Aha…”).

    左:新用户注册。 您会看到他的标识符(电子邮件地址)。 它链接到唯一的UID( “ lC27Aha…” )。

  2. Right: Then, the user adds two items to his shopping list: Milk and Apples. Each change made by a client flashes in color — in real-time!

    正确:然后,用户将两个商品添加到他的购物清单中:牛奶和苹果。 客户所做的每个更改都会实时闪烁颜色!

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第12张图片

The hierarchy of the JSON model is as follows:

JSON模型的层次结构如下:

  1. shoppinglist-vplay: root node of your database. Its name is the project ID you used when creating the Firebase project.

    shoppinglist-vplay:数据库的根节点。 它的名称是您在创建Firebase项目时使用的项目ID。

  2. users: added through the authentication part. Keeps data separate for each registered user. The key is the UID of the user. The database itself doesn’t contain the email-address of the user.

    用户:通过身份验证部分添加。 将每个注册用户的数据分开。 密钥是用户的UID。 数据库本身不包含用户的电子邮件地址。

  3. shoppinglist-user: root database key, accessible by the individual logged in user. The name is set by the application, as you will do in the next step.

    shoppinglist-user:根数据库密钥,个人登录用户可以访问。 该名称由应用程序设置,就像您在下一步中所做的那样。

  4. : in the shopping list scenario, you can use the timestamp as the unique key. The node contains two children:

    在购物清单场景中,您可以将时间戳记用作唯一键。 该节点包含两个子节点:

a. Timestamp (where you could save the last modification time)

一个。 时间戳记(您可以在其中保存上次修改时间)

b. Actual item to buy (string)

b。 实际要购买的物品(字符串)

This is the default hierarchy, based on customizable rules. But, you have full control to customize every aspect.

这是基于可自定义规则的默认层次结构。 但是,您可以完全控制自定义各个方面 。

连接到Firebase实时数据库 (Connect to the Firebase Realtime Database)

The interface to Firebase is powerful. All connected clients get real-time updates. Plus, it offers full offline-support. When the user goes online again, the changes sync to the cloud.

Firebase的界面功能强大。 所有连接的客户端均获得实时更新。 另外,它提供了完整的脱机支持。 当用户再次上线时,更改将同步到云。

Felgo includes a single item that works across Android and iOS. Especially for multi-platform scenarios, you’ll love this.

Felgo包含可在Android和iOS上使用的单个项目。 特别是对于多平台方案,您会喜欢上它。

The FirebaseDatabase QML type offers methods to retrieve and update the JSON tree in the Firebase cloud. Callbacks inform you whenever the items changed and when operations complete.

FirebaseDatabase QML类型提供了在Firebase云中检索和更新JSON树的方法。 每当项目更改以及操作完成时,回调都会通知您。

In your app architecture, you set up a data flow from the user interface to the Firebase database in the cloud:

在您的应用程序体系结构中,您设置了从用户界面到云中Firebase数据库的数据流:

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第13张图片

A “+” button in the navigation bar (1) triggers an input dialog (2). It sends the new shopping item name to the DataModel. The DataModel abstracts the Firebase Realtime database (3). The FirebaseDatabase item from Felgo performs the cloud interaction (4).

导航栏中的“ +”按钮(1)触发输入对话框(2)。 它将新的购物商品名称发送到DataModel。 DataModel抽象了Firebase Realtime数据库(3)。 Felgo的FirebaseDatabase项执行云交互(4)。

Whenever the model data in the cloud changes, your app gets a callback (5). This updates the cached list of shopping items (6).

每当云中的模型数据发生更改时,您的应用程序都会获得回调(5)。 这将更新购物项目的缓存列表(6)。

Firebase数据库配置和项目存储 (Firebase Database Configuration & Item Storage)

Add the following code snippet to your DataModel:

将以下代码片段添加到您的DataModel中:

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

The FirebaseDatabase item (with id database) requires a reference ( config) to the generic Firebase connection configuration item with your app keys.

FirebaseDatabase项(具有id database )需要使用您的应用程序密钥对通用Firebase连接配置项的引用( config )。

Firebase实时更新 (Firebase Realtime Updates)

Your app registers for real time updates by adding keys to the realtimeUserValueKeys property.

您的应用程序通过将密钥添加到realtimeUserValueKeys属性来注册实时更新。

The realtimeUserValueChanged signal fires every time the monitored keys change. E.g., by another family member sharing your shopping list account. The signal is also emitted when the connection to the database is ready after a successful login. So, it’s the only method we need to retrieve & update the shopping list items!

每当监视的键更改时,都会触发realtimeUserValueChanged信号 。 例如,由另一个家庭成员共享您的购物清单帐户。 成功登录后,与数据库的连接准备就绪时,也会发出该信号。 因此,这是我们检索和更新购物清单项目的唯一方法!

The shoppingItemsLoaded(value) function then assigns the items to a public property of the DataModel. It also ensures the list never gets null by using an empty array “{}” in case no shopping items have been created so far.

然后, shoppingItemsLoaded(value)函数将项目分配给DataModel的公共属性。 它还确保列表不会被使用空数组被 “{}”的情况下,没有购物项目已创建至今。

For debugging, you can print the raw JSON data to the console. During development, this helps to see what Firebase transmits to your app. In the video example above, this would be:

为了进行调试,您可以将原始JSON数据打印到控制台。 在开发过程中,这有助于查看Firebase传输到您的应用程序的内容。 在上面的视频示例中,这将是:

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

准备购物清单页面(MasterPage) (Prepare the Shopping List Page (MasterPage))

The Felgo wizard already created the basic structure of a master list / detail app. You can use this as a base for customizing it to the shopping list scenario.

Felgo向导已经创建了主列表/详细信息应用程序的基本结构。 您可以以此为基础将其自定义为购物清单方案。

You need the following functionality:

您需要以下功能:

List of shopping items

购物清单

  • Tap an item to navigate to the detail page. You can edit the item there.

    点击一个项目以导航到详细信息页面。 您可以在那里编辑项目。
  • Swipe the item to the left to reveal the delete button.

    向左滑动项目以显示删除按钮。

“Add” (+) button. Creates a new shopping item.

“添加”(+)按钮。 创建一个新的购物商品。

添加购物商品 (Add Shopping Items)

You assign the keys of the dataModel.shoppingItems array as the model for the list view. The “ListPage” instantiates rows for each item in the model.

您将dataModel.shoppingItems数组的键分配为列表视图的模型。 “ ListPage”实例化模型中每个项目的行。

The minimal code of the MasterPage:

母版页的最小代码:

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

You start with adding shopping items to your Firebase Realtime Database. The “+” button appears in the navigation bar. You achieve this through the rightBarItem, provided by the base Page QML type. Make your life even easier by using the predefined IconType.plus symbol. Thanks to Felgo’s multi-platform support, the button is always placed in the correct screen area for Android and iOS.

首先,将购物商品添加到Firebase实时数据库中。 “ +”按钮出现在导航栏中。 您可以通过基本Page QML类型提供的rightBarItem实现此目的。 使用预定义的IconType.plus符号可使您的生活更加轻松。 感谢Felgo的多平台支持,该按钮始终放置在适用于Android和iOS的正确屏幕区域中。

To enjoy even more pre-built functionality, use the ListPage QML type as base item of this QML file. “ListPage” derives from the more generic Page type. On top of the generic Page, it includes a full-screen AppListView item. It’ll contain all your shopping items. Plus, it even offers advanced features like fully-animated pull-to-refresh.

要享受更多的预建功能,请使用ListPage QML类型作为此QML文件的基础项目。 “ ListPage”派生自更通用的Page类型 。 在通用页面的顶部,它包括一个全屏AppListView项目 。 它将包含您所有的购物物品。 另外,它甚至还提供高级功能,例如完全动画化的“拉动刷新”。

When the user taps the “+” button, your app shows a simple single-line text entry dialog ( InputDialog).

当用户点击“ +”按钮时,您的应用程序将显示一个简单的单行文本输入对话框( InputDialog )。

将购物商品存储在Firebase实时数据库中 (Store Shopping Items in the Firebase Realtime Database)

For a good architecture, you send the user’s new shopping item via a signal to the DataModel. So, define a signal addNewShoppingItem(string text) in the ListPage (with id masterPage). The callback function of the InputDialog then emits the signal. It sends the text entered by the user as parameter.

为了获得良好的架构,您可以通过信号将用户的新购物商品发送到DataModel 。 因此,在ListPage中定义一个信号addNewShoppingItem(字符串文本) (ID为masterPage )。 然后,InputDialog的回调函数将发出信号。 它发送用户输入的文本作为参数。

Now, connect the MasterPage’s signal to the DataModel’s slot. Like before for the login, define it in Main.qml. Extend your previous MasterPage definition in Main.qml:

现在,将MasterPage的信号连接到DataModel的插槽。 像以前的登录一样,在Main.qml中定义它。 在Main.qml中扩展先前的MasterPage定义:

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

Again, the most interesting code is in DataModel. It stores the new shopping item in the Firebase Realtime Database. Add this method to your DataModel:

同样,最有趣的代码是在DataModel中。 它将新的购物商品存储在Firebase实时数据库中。 将此方法添加到您的DataModel中:

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

The addShoppingItem function constructs an object “shoppingItem”. The method database.setUserValue() serializes it to JSON. Next, it’s sent to the Firebase database in the cloud. The setUserValue() method has three parameters:

addShoppingItem函数构造一个对象“ shoppingItem”。 方法database.setUserValue()将其序列化为JSON。 接下来,将其发送到云中的Firebase数据库。 setUserValue()方法具有三个参数:

  1. The root node in the user’s JSON tree is “shoppinglist-user”. As the key, you can re-use the time stamp; you can be certain that it’s a unique identifier.

    用户的JSON树中的根节点是“ shoppinglist-user”。 作为密钥,您可以重新使用时间戳; 您可以确定它是唯一标识符。
  2. Contains the key/value pairs to store in the database.

    包含要存储在数据库中的键/值对。
  3. Your simple shopping list app doesn’t show that an operation is in progress. You could activate an animation when you send the data. Stop it again when you receive the loadingFinished callback. To get started, log the info to the console.

    您的简单购物清单应用不会显示操作正在进行中。 发送数据时可以激活动画。 收到loadingFinished回调时,再次停止它。 首先,将信息记录到控制台。

列出您应用中的购物商品 (List Shopping Items in Your App)

Your app already adds items to the real time database in the cloud. The last major feature is the UI to show the shopping items!

您的应用程序已将项目添加到云中的实时数据库中。 最后一个主要功能是显示购物商品的UI!

Back in MasterPage.qml, extend the code of ListPage with a delegate. The delegate instantiates for each individual item in your shopping list.

返回MasterPage.qml ,使用委托扩展ListPage的代码。 代表将实例化购物清单中的每个单独项目。

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

The SwipeOptionsContainer QML item supports swipeable list rows in Android and iOS apps. In the next step, you will add the feature to delete the item through the swipe gesture.

SwipeOptionsContainer QML项支持Android和iOS应用中的可滑动列表行。 在下一步中,您将添加功能以通过滑动手势删除项目。

Usually, list items have a very simple structure: one or two lines of text, plus an optional image. The Felgo item SimpleRow provides a ready-made layout. The three corresponding properties are: text, detailText and icon.

通常,列表项的结构非常简单:一两行文字以及可选的图片。 Felgo项目SimpleRow提供了现成的布局。 对应的三个属性是: textdetailTexticon

There’s one simple trick you need to be aware of. How to access the entire individual properties of the currently shown item? The model you assigned to the ListPage only contained the keys. But, the line needs to access the full data of the shopping item! This includes the name and the date.

您需要了解一个简单的技巧。 如何访问当前显示项目的全部单个属性? 您分配给ListPage的模型仅包含键。 但是,生产线需要访问购物商品的全部数据! 这包括名称和日期。

Where can you get the complete data? It’s stored in the DataModel. Thus, you access it based on the key stored in the list view model. The relevant item data is then available through the readonly property shoppingItem. Its declaration is part of the delegate you inserted a moment ago. This is the relevant line, for reference:

您在哪里可以获得完整的数据? 它存储在DataModel中 。 因此,您可以基于存储在列表视图模型中的键来访问它。 然后可以通过只读属性shoppingItem获得相关的项目数据。 它的声明是您刚才插入的代表的一部分。 这是相关的行,以供参考:

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

Here, you see your app in action:

在这里,您可以看到正在运行的应用程序:

After the user logs in to the app on the phone, he adds an item with the text “Felgo” to the shopping items list. Thanks to the real-time database features, the item immediately appears in the web view. Google highlights it in green to make you aware of the change.

用户登录到手机上的应用程序后,他将带有文本“ Felgo”的商品添加到购物清单。 由于具有实时数据库功能,该项目立即显示在Web视图中。 Google以绿色突出显示它,使您知道更改。

Even more amazing: real-time changes also work in the other direction. Try deleting a shopping item in the database view on the web. It’ll immediately disappear on the smartphone. No extra code was necessary. In DataModel, Felgo’s FirebaseDatabase item emits a signal every time the remote database changes. In your app, you reload the data based on its new contents.

更令人惊奇的是:实时更改也可以在另一个方向上起作用。 尝试在网络上的数据库视图中删除购物商品。 它会立即在智能手机上消失。 无需额外的代码。 在DataModel中 ,每次远程数据库更改时,Felgo的FirebaseDatabase项都会发出一个信号。 在您的应用中,您将根据其新内容重新加载数据。

从NoSQL Firebase数据库中删除项目 (Delete Items from the NoSQL Firebase Database)

Your app already handles real-time updates from the web. Now, the final extension for you to write: let the user delete the shopping items from the phone!

您的应用程序已经可以处理来自网络的实时更新。 现在,您可以编写的最后一个扩展名是:让用户从手机中删除购物商品!

The SwipeOptionsContainer for the ListPage items contains useful out-of-the-box functionality. Like many other advanced apps, users can swipe the item to a side. In your QML, you specify the item to appear. In this case, choose a SwipeButton with red background color and an “X” icon. Now, whenever the user swipes and clicks on the delete button, its onClicked slot executes.

ListPage项的SwipeOptionsContainer包含有用的即用型功能。 像许多其他高级应用程序一样,用户可以将项目滑动到侧面。 在您的QML中,您指定要显示的项目。 在这种情况下,请选择带有红色背景色和“ X”图标的SwipeButton 。 现在,只要用户滑动并单击删除按钮, 就会执行其onClicked插槽。

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

In the onClicked slot, you must inform the real-time database about the deleted item. For this, add a second new signal for the ListPage item in the MasterPage:

在onClicked插槽中,您必须将删除的项目告知实时数据库。 为此,在MasterPage中ListPage项目添加第二个新信号:

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

As parameter, your code sends the ID of the item to delete. Remember — we used the creation date as unique ID!

作为参数,您的代码发送要删除的项目的ID。 请记住-我们使用创建日期作为唯一ID!

The app must forward the signal to the data model. This architecture keeps the view separated from the model. So, extend the MasterPage component in Main.qml to forward the signal. For reference, this is what the complete component definition looks like now:

应用必须将信号转发到数据模型。 这种架构使视图与模型分离。 因此,扩展Main.qml中MasterPage组件以转发信号。 作为参考,下面是完整的组件定义:

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

Like adding a shopping item, the signal triggers a JavaScript function in the data model. To stick to the naming scheme, call it deleteShoppingItem(id).

就像添加购物商品一样,该信号会触发数据模型中JavaScript函数。 要坚持命名方案, 请将其命名为deleteShoppingItem(id)

As a final step, jump into DataModel.qml and add the function implementation. It’s only one line and resembles the call to add an item. The only difference: instead of setting the item data as value in the database, you now send null. The result: the item is deleted.

最后一步,进入DataModel.qml并添加函数实现。 它只有一行,类似于添加项的调用。 唯一的区别是:现在,您发送null而不是将项目数据设置为数据库中的 。 结果:该项目被删除。

Run this code on your iOS or Android device now, with Live Code Reloading 立即通过实时代码重新加载在您的iOS或Android设备上 运行此代码

The animation below shows how deleting item on the phone works. Again, the left side shows the real-time database view of Firebase on the web. Items instantly disappear in the web view when the user has deleted them on the phone.

以下动画显示了如何删除手机上的项目。 同样,左侧显示了Web上Firebase的实时数据库视图。 用户在手机上删除项目后,这些项目会立即在Web视图中消失。

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第14张图片

走得更远 (Going Further)

Your cross-platform shopping list app is powerful:

您的跨平台购物清单应用程序功能强大:

  • It features an efficient UI to create new items.

    它具有有效的UI来创建新项目。
  • Delete items through an intuitive swipe gesture.

    通过直观的滑动手势删除项目。
  • All changes immediately sync to & from the cloud database.

    所有更改都会立即与云数据库同步并从云数据库同步。
  • Share the login with your family. Everyone will be up-to-date.

    与家人分享登录信息。 每个人都是最新的。

For shopping lists, it’s not needed too often. But, for other use cases you might also want to include functionality to edit items. As a bonus, we’ve added the necessary code to the full example on GitHub. Check it out to see how modifying existing items works! Also, the open source example is a great reference, as it includes extra code comments.

对于购物清单,不需要太频繁。 但是,对于其他用例,您可能还希望包括编辑项目的功能。 另外,我们在GitHub的完整示例中添加了必要的代码。 检查一下,看看如何修改现有项目! 另外,开源示例是一个很好的参考,因为它包含了额外的代码注释。

By combining the Firebase real-time database with Qt and Felgo, you gain support for user authentication and shared NoSQL-databases with a few lines of code. If you’d also like to store larger files in the cloud, check out the FirebaseStorage QML type.

通过将Firebase实时数据库与Qt和Felgo结合使用,您可以通过几行代码获得对用户身份验证和共享NoSQL数据库的支持。 如果您还想将更大的文件存储在云中,请查看FirebaseStorage QML类型 。

像这样的更多帖子 (More Posts Like This)

firebase ios_适用于Android和iOS的Firebase实时数据库登录教程_第15张图片

Machine Learning: Add Image Classification for iOS and Android with Qt and TensorFlow

机器学习:使用Qt和TensorFlow为iOS和Android添加图像分类

Image for post

Qt AR: Why and How to Add Augmented Reality to Your Mobile App

Qt AR:为什么以及如何向您的移动应用程序添加增强现实

Release 2.17.0: Firebase Cloud Storage, Downloadable Resources at Runtime and Native File Access on All Platforms

版本2.17.0:Firebase云存储,运行时可下载的资源以及所有平台上的本机文件访问

Originally published at https://felgo.com on April 18, 2020.

最初于 2020年4月18日 https://felgo.com 发布

翻译自: https://medium.com/swlh/firebase-realtime-database-login-tutorial-for-android-and-ios-4a5407602b5e

firebase ios

你可能感兴趣的:(数据库,python,android,人工智能,mysql)