Menu Docs
Página inicial do Docs
/ /
Atlas Device SDKs
/ /

Chamar uma função - Swift SDK

Nesta página

  • Chamar uma função por nome
  • Deixar assíncrono/Aguardar chamada de função

Importante

Certifique-se de limpar os dados do cliente para se proteger contra a injeção de código ao usar funções.

Consider an Atlas App Services Function named concatenate that takes two arguments, concatenates them, and returns the result:

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

Para executar uma função do Swift SDK, use o objeto functions no usuário conectado no momento.

O objeto functions tem membros dinâmicos correspondentes a funções. Neste caso, functions.concatenate() refere-se à função concatenate . Passe um BSONArray de argumentos. O fechamento à direita é o manipulador de conclusão a ser chamado quando a chamada de função estiver concluída. Este manipulador é executado em um DispatchQueue global não 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")
}

Novidade na versão 10.16.0.

O Realm Swift SDK oferece versões async/await dos 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 das versões 10.15.0 e 10.16.0 do SDK do Realm Swift, muitas das APIs do Realm suportam a sintaxe async/await do Swift. Os projetos devem atender a estes requisitos:

Versão do Swift SDK
Requisito de versão do Swift
Sistema operacional compatível
10.25.0
Swift 5.6
iOS 13.x
10.15.0 ou 10.16.0
Swift 5.5
iOS 15.x

Se a sua aplicação acessar Realm em um contexto do async/await, marque o código com @MainActor para evitar falhas relacionadas a threading.

Voltar

Conectar a um aplicativo do App Services

Próximo

Consulta MongoDB