调用函数 - Swift SDK
Realm 现已更名为 Atlas Device SDK – 了解详情
按名称调用函数
重要
使用函数时,确保对客户端数据进行清理,以防止代码注入。
考虑一个名为 concatenate
的Atlas App Services 函数,它接受两个参数,将它们连接起来,然后返回结果:
// concatenate: concatenate two strings exports = function(a, b) { return a + b; };
要执行 Swift SDK 中的函数,请对当前登录用户使用functions
对象。
functions
对象具有与函数相对应的动态成员。 在本例中, functions.concatenate()
指的是concatenate
函数。 传递BSONArray
参数。 尾随闭包是函数调用完成时要调用的完成处理程序。 此处理程序在非主全局DispatchQueue
上执行。
异步/等待调用函数
版本 10.16.0 中的新增内容。
Realm Swift SDK 提供了User.function
方法的异步/等待版本。
func testAsyncCallFunction() async { let app = App(id: YOUR_APP_SERVICES_APP_ID) // ... log in ... let user = app.currentUser! do { // The dynamic member name `concatenate` is directly associated with the // function name. The first argument is the `BSONArray` of arguments to be // provided to the function - in this case, a string that represents a // username and a string that represents an email domain. let concatenatedString = try await user.functions.concatenate([AnyBSON("john.smith"), AnyBSON("@companyemail.com")]) print("Called function 'concatenate' and got result: \(concatenatedString)") assert(concatenatedString == "john.smith@companyemail.com") } catch { print("Function call failed: \(error.localizedDescription)") } }
从 Realm Swift SDK 10.15.0 和 10.16.0 版本开始,很多 Realm API 均支持 Swift“异步/等待”语法。项目必须符合以下要求:
Swift SDK 版本 | Swift 版本要求 | 支持的操作系统 |
---|---|---|
10.25.0 | Swift 5.6 | iOS 13.x |
10.15.0 或 10.16.0 | Swift 5.5 | iOS 15.x |
如果您的应用会在 async/await
上下文中访问 Realm,请使用 @MainActor
来标记此代码,从而避免出现与线程相关的崩溃。