Navigation

Call a Function - iOS SDK

Consider a Realm function named sum that takes two arguments, adds them, and returns the result:

// sum: adds two numbers
exports = function(a, b) {
return a + b;
};

To execute a function from the iOS Client SDK, use the functions object on the currently logged-in user.

The functions object has dynamic members corresponding to functions. In this case, functions.sum() refers to the sum function. Pass a BSONArray of arguments. The trailing closure is the completion handler to call when the function call is complete. This handler is executed on a non-main global DispatchQueue.

let app = App(id: YOUR_REALM_APP_ID)
// ... log in ...
let user = app.currentUser!
// The dynamic member name `sum` is directly associated with the function
// name. The first argument is the `BSONArray` of arguments to be provided
// to the function. The trailing closure is the completion handler
// to call when the function call is complete. This handler is executed on
// a non-main global `DispatchQueue`.
user.functions.sum([1, 2]) { sum, error in
guard error == nil else {
print("Function call failed: \(error!.localizedDescription)")
return
}
guard case let .int64(value) = sum else {
print("Unexpected non-int64 result: \(sum ?? "nil")")
return
}
print("Called function 'sum' and got result: \(value)")
assert(value == 3)
}
Give Feedback