如何使用swiftui构建聊天应用程序第1部分

In this tutorial, we’ll build a simple chat application for iOS and macOS using SwiftUI and Stream Chat’s Swift SDK. Although Stream provides a suite of UIKit components that work out-of-the-box, we can use use the low-level client to develop custom components with SwiftUI.

在本教程中,我们将使用SwiftUI和Stream Chat的Swift SDK为iOS和macOS构建一个简单的聊天应用程序。 尽管Stream提供了一现成可用的UIKit组件 ,但是我们可以使用低级客户端通过SwiftUI开发自定义组件。

If you get lost during this tutorial, you can check the completed project in this GitHub repo.

如果您在本教程中迷路了,可以在此GitHub存储库中检查已完成的项目。

什么是SwiftUI? (What is SwiftUI?)

“SwiftUI is an innovative, exceptionally simple way to build user interfaces across all Apple platforms with the power of Swift. Build user interfaces for any Apple device using just one set of tools and APIs. With a declarative Swift syntax that’s easy to read and natural to write, SwiftUI works seamlessly with new Xcode design tools to keep your code and design perfectly in sync. Automatic support for Dynamic Type, Dark Mode, localization, and accessibility means your first line of SwiftUI code is already the most powerful UI code you’ve ever written.”

“ SwiftUI是一种创新的,非常简单的方法,它借助Swift的功能在所有Apple平台上构建用户界面。 仅使用一组工具和API为任何Apple设备构建用户界面。 SwiftUI具有易于阅读且易于编写的声明式Swift语法,可与新的Xcode设计工具无缝协作,以使您的代码和设计完美同步。 自动支持动态类型,暗模式,本地化和可访问性,这意味着您的SwiftUI代码的第一行已经是您编写过的功能最强大的UI代码。”

- Apple Developer Portal: SwiftUI

-Apple开发人员门户:SwiftUI

你需要什么 (What you need)

  • iOS 13+

    iOS 13以上
  • Xcode 11+

    Xcode 11以上
  • A Stream account

    帐号

Want to read this story later? Save it in Journal.

想稍后再读这个故事吗? 将其保存在 Journal中

步骤1:设置Xcode项目 (Step 1: Set up the Xcode project)

To start, let’s create a SwiftUI project in Xcode.

首先,让我们在Xcode中创建一个SwiftUI项目。

Select ‘Single View App’.

选择“单视图应用”。

Image for post

And make sure to select ‘SwiftUI’ for the User Interface.

并确保为用户界面选择“ SwiftUI”。

Image for post

步骤2:设置流聊天依赖性 (Step 2: Set up the Stream Chat dependency)

To install the Stream Chat dependency, we’ll use CocoaPods. If you prefer Carthage or Swift Package Manager, they’re also supported.

要安装Stream Chat依赖项,我们将使用CocoaPods 。 如果您喜欢Carthage或Swift Package Manager,则也支持它们。

In the folder where you saved the project, run pod init and add StreamChat to the Podfile. It should look similar to this:

在保存项目的文件夹中,运行pod init并将StreamChat添加到Podfile 。 它看起来应该类似于:

After you do that, run pod install, wait a bit for it to finish, and open the project via the .xcworkspace that was created.

完成此操作后,运行pod install ,稍等片刻,然后通过创建的.xcworkspace打开项目。

步骤3:配置流聊天仪表板 (Step 3: Configure the Stream Chat Dashboard)

Sign up at GetStream.io, create the application, and make sure to select development instead of production.

GetStream.io上注册,创建应用程序,并确保选择开发而不是生产。

Image for post

To make things simple for now, let’s disable both auth checks and permission checks. Make sure to hit save. When your app is in production, you should keep these enabled.

为了使事情现在变得简单,让我们同时禁用身份验证检查和权限检查。 确保点击保存。 当您的应用程序投入生产时,应保持启用状态。

Image for post

For future reference, you can see the documentation about authentication here and permissions here.

对于未来的参考,你可以看到有关身份验证的文件在这里和权限这里

Now, save your credentials, as we’ll need them to power the chat in the app. Since we disabled auth and permissions, we’ll only really need the key for now, but in production, you’ll use the secret in your backend to create JWTs to allow users to interact with your app securely.

现在,保存您的凭据,因为我们需要它们来增强应用程序中的聊天功能。 由于我们已禁用身份验证和权限,因此目前我们仅真正需要密钥,但是在生产中,您将使用后端中的密钥创建JWT,以允许用户安全地与您的应用进行交互。

Image for post

As you can see, I’ve blacked out my keys. You should make sure to keep your credentials safe.

如您所见,我已经把钥匙涂黑了。 您应该确保自己的凭据安全。

步骤4:配置Stream Chat SDK (Step 4: Configure Stream Chat SDK)

Now that we’ve set up the project and Stream Chat dashboard let’s configure the SDK’s singleton with the Stream Chat App’s key. The didFinishLaunchingWithOptions function in AppDelegate.swift should look similar to the following snippet.

现在我们已经设置了项目和Stream Chat仪表板,让我们使用Stream Chat App的键配置SDK的单例。 该didFinishLaunchingWithOptions函数AppDelegate.swift应类似于下面的代码片段。

That will configure the Client.shared instance, which we'll use throughout this tutorial to make calls to the Stream Chat API and subscribe to events.

这将配置Client.shared实例,我们将在整个教程中使用该实例来调用Stream Chat API并订阅事件。

步骤5:创建登录视图 (Step 5: Create the Login View)

Finally, we can start using the power of SwiftUI to build the login screen, which will look similar to the following screenshot.

最后,我们可以开始使用SwiftUI的功能来构建登录屏幕,其外观类似于以下屏幕截图。

Image for post

Let’s create a LoginView.swift file and paste the following contents.

让我们创建一个LoginView.swift文件并粘贴以下内容。

In that snippet of code, we create a TextField and a Button. The Button calls Client.shared.set(user:) with the contents of the TextField for the username. The callback to that function, if successful, will trigger the NavigationLink to the ChatView which we'll create in the next step.

在这段代码中,我们创建了一个TextField和一个Button 。 按钮使用用户名的TextField内容调用Client.shared.set(user:) 。 如果成功,则对该函数的回调将触发NavigationLink到我们将在下一步中创建的ChatView

Note we’re not collecting a password since we’re skipping authentication for this tutorial, so anyone can log in as the username they choose. Also, usernames may not contains spaces and some special characters. It would be best if you handled the possible errors.

请注意,由于我们跳过了本教程的身份验证,因此我们没有收集密码,因此任何人都可以使用他们选择的用户名登录。 此外,用户名可能不包含空格和某些特殊字符。 最好处理可能的错误。

步骤6:建立即时通讯检视 (Step 6: Create the Chat View)

For this first part, we’ll have a single channel that the user joins as soon as they log in. It will look similar to the screenshot below. We’ll make it look a bit cozier in the next step.

对于第一部分,我们将有一个用户登录后立即加入的单一渠道。其外观类似于下面的屏幕截图。 在下一步中,我们将使其看起来更加舒适。

Image for post

Let’s create a ChatView.swift file and paste the contents below.

让我们创建一个ChatView.swift文件并将其内容粘贴到下面。

In that snippet, all we do is create a List for the messages and a simple composer with a TextField and a Button that sends the message with the function Client.shared.send(message:). We also add a callback for the onAppear of this View, which watches the channel with channel.watch(options:), which allows us to receive .messageNew events with channel.subscribe(forEvents:). We now have a functioning chat, though the UI can be improved.

在该代码段中,我们要做的就是为消息创建一个List ,以及一个简单的Client.shared.send(message:) ,一个TextField和一个Button,后者使用功能Client.shared.send(message:) 。 我们还为此视图的onAppear添加了一个回调,该回调使用channel.watch(options:) .messageNew channel.subscribe(forEvents:) ,这使我们可以通过channel.subscribe(forEvents:)接收.messageNew事件。 现在,我们可以进行正常的聊天,尽管可以改进UI。

步骤7:改善讯息介面 (Step 7: Improving the message UI)

Instead of that simple text cell, let’s create a custom view for it, similar to how it’s displayed in iMessage. It will look comparable to this screenshot.

让我们为其创建一个自定义视图,而不是简单的文本单元格,类似于在iMessage中显示它的方式。 它看起来将与此屏幕截图相当。

Image for post

Create MessageView.swift and paste the following contents.

创建MessageView.swift并粘贴以下内容。

After that, replace the line Text("\($0.user.id): \($0.text)") in ChatView.swift with MessageView(message: $0).

在此之后,更换行Text("\($0.user.id): \($0.text)")ChatView.swiftMessageView(message: $0)

To remove the separators between the messages, you’ll need to run this call before displaying the chat screen: UITableView.appearance().separatorStyle = .none. I suggest you put it in AppDelegate.swift, next to where you configure the Stream Chat Client.

要删除消息之间的分隔符,您需要在显示聊天屏幕之前运行此调用: UITableView.appearance().separatorStyle = .none 。 建议您将其放在AppDelegate.swift ,在配置Stream Chat Client的位置旁边。

结语 (Wrapping up)

Congratulations! You’ve built the basis of a functioning chat app with SwiftUI and Stream. In part two, we’ll make a UI for creating and selecting channels. Stay tuned! Meanwhile, I encourage you to browse through Stream Chat’s docs and experiment with the project you just built.

恭喜你! 您已经使用SwiftUI和Stream构建了功能正常的聊天应用程序的基础。 在第二部分中,我们将创建一个用于创建和选择通道的UI。 敬请关注! 同时,我鼓励您浏览Stream Chat的文档并尝试使用刚刚构建的项目。

Originally published at https://getstream.io.

最初发布在 https://getstream.io

Image for post

📝 Save this story in Journal.

story将这个故事保存在Journal中

👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. Read the Noteworthy in Tech newsletter.

every‍💻每个星期天早晨,您都可以在收件箱中等待本周最值得关注的Tech故事。 阅读Tech Newsletter中的“值得注意”

翻译自: https://blog.usejournal.com/how-to-build-a-chat-app-with-swiftui-part-1-eb7cb8532242

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值