ios - 如何从 iOS (Swift) 连接到 MongoDB

我使用 RealmSwift 开发了一个 iOS 应用程序。 到目前为止效果很好。 现在,随着我越来越接近发布到 App Store,我想设置一些云配置以便能够连接到云数据库,但我完全搞糊涂了。

几周前,我看到了 Realm Cloud 作为一个选项。现在我只看到 MongoDB Realm - 或类似的东西。我仔细研究了一下,发现有三个组件:Realm DB、Realm Sync 和 Mongo DB Atlas。

如果我的理解是正确的,我必须创建一个 Atlas 集群,我的 Realm 数据库将托管在该集群上,我将能够连接和同步到该集群。我说得对吗?

我的主要问题是我不知道如何将它连接到我现有的代码。我不需要用户身份验证或来自 MongoDB 的任何东西,我有自己的,我基本上只有一个数据库,我想同步和连接到它。所以,目前在我通常使用的代码中:

let realm = try! Realm()
try! realm.write {
   ...
}

如何更新它以使用 Atlas Cloud 中的 MongoDB?我浏览了他们的“教程”,但我仍然很困惑。

我看到一个 Realm(configuration: Realm.Configuration) 初始化函数,但如果我应该使用那个,我应该如何获得一个 Realm.Configuration 对象?

另外,分区键是什么意思?

非常感谢。

最佳答案

你的困惑是有道理的。文档和教程仍在进行中,并且有点脱节。我认为随着时间的推移它会有所改善。

SO 不是完整教程的好地方,但这里有一个非常高层次的概述。

教程链接 - iOS Swift Tutorial

完成 Cocoapods 安装

1) 您将在 MongoDB 控制台中创建一个集群

2) 在该集群中,您将创建一个 Realm“应用程序”

3) 在您要设置的 Realm “应用程序”中:

  • 同步(开发模式)

  • 用户->提供商->电子邮件/密码验证

您的应用程序将有一个 AppId,可以在左侧的 Atlas 控制台中找到,就在应用程序名称旁边(这是一个文档按钮,您可以点击它进行复制)。

然后,在您的 XCode Realm 项目中,您将使用 cocoapods 设置它以安装 RealmSwift。

现在回答你的问题:

how to connect it to my existing code.

添加一个结构,它是你的 Atlas Realm 项目的连接字符串

导入 RealmSwift

struct Constants {
    // Set this to your Realm App ID found in the Realm UI.
    static let REALM_APP_ID = "your app id"
}

然后,当你想认证时,你会这样做

let app = RealmApp(id: Constants.REALM_APP_ID)
app.login(withCredential: AppCredentials(username: username, password: password)) { user, error in

一旦你通过身份验证,访问 Realm 使用这个

guard let user = app.currentUser() else {
   fatalError("Must be logged in to access this view")
}

let realm = try! Realm(configuration: user.configuration(partitionValue: user.identity!))

https://stackoverflow.com/questions/62375536/

相关文章:

php - 如何在 laravel 中检测 JFIF 图像类型

reactjs - WebSocket SocketIO 连接无法与 Heroku 上的 NestJ

ios - iOS 13 的 iOS 多任务 View 中的错误应用程序图标

linux - docker 内部出现 fatal error : unable to access

c# - 开拓者。如何在 Startup 类(方法 ConfigureServices)中获取当前

tensorflow - TensorFlow 2 和 Keras 中不同的正向和反向传播

r - H2O 在 R 中连接失败

python - 获取实例的类名

javascript - 单击 jpg 图像时尝试使用 EXIF.js 返回 GPS 坐标

vue.js - 在 Vue 中安装不想给 $route.name