Docs Menu
Docs Home
/ /
Servicios de aplicaciones

Llamar a una función - Swift SDK

Importante

Asegúrese de desinfectar los datos del cliente para protegerlos contra la inyección de código al usar funciones.

Considere una Función de servicios de aplicaciones Atlas denominada concatenate que toma dos argumentos, los concatena y devuelve el resultado:

// concatenate: concatenate two strings
exports = function(a, b) {
return a + b;
};

Para ejecutar una función desde el SDK de Swift, utilice el objeto functions en el usuario que ha iniciado sesión actualmente.

El objeto functions tiene miembros dinámicos que corresponden a funciones. En este caso, functions.concatenate() hace referencia a la función concatenate. Pase un BSONArray de argumentos. El cierre final es el controlador de finalización que se llama cuando se completa la llamada a la función. Este controlador se ejecuta en una variable global DispatchQueue no principal.

RLMApp *app = [RLMApp appWithId:YOUR_APP_ID];
// ... log in ...
RLMUser *user = [app currentUser];
// Call concatenate function
[user callFunctionNamed:@"concatenate"
arguments:@[@"john.smith", @"@companyemail.com"]
completionBlock:^(id<RLMBSON> result, NSError *error) {
if (error) {
NSLog(@"Function call failed: %@", [error localizedDescription]);
return;
}
NSLog(@"Called function 'concatenate' and got result: %@", result);
assert([result isEqual:@"john.smith@companyemail.com"]);
}];
let app = App(id: YOUR_APP_SERVICES_APP_ID)
// ... log in ...
let user = app.currentUser!
// 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.
// 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.concatenate([AnyBSON("john.smith"), AnyBSON("@companyemail.com")]) { concatenate, error in
guard error == nil else {
print("Function call failed: \(error!.localizedDescription)")
return
}
guard case let .string(value) = concatenate else {
print("Unexpected non-string result: \(concatenate ?? "nil")")
return
}
print("Called function 'concatenate' and got result: \(value)")
assert(value == "john.smith@companyemail.com")
}

Nuevo en la versión 10.16.0.

El SDK Realm Swift ofrece versiones async/await de los métodos 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)")
}
}

A partir de las versiones 10.15.0 y 10.16.0 del SDK de Realm Swift, muchas de las API de Realm admiten la sintaxis async/await de Swift. Los proyectos deben cumplir estos requisitos:

Versión del SDK de Swift
Requisito de versión Swift
Sistema operativo compatible

10.25.0

Swift 5.6

iOS 13.x

10.15.0 o 10.16.0

Swift 5.5

iOS 15.x

Si su aplicación accede a Realm en un contexto async/await, marque el código con @MainActor para evitar fallas relacionadas con subprocesos.

Volver

Conectarse a una aplicación de servicios de aplicaciones

En esta página