Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
É possível usar o kit de aprendizado de máquina para traduzir texto entre idiomas. Atualmente, o Kit de ML
oferece suporte para a tradução entre
59 idiomas.
Antes de começar
Se você ainda não adicionou o Firebase ao seu app, siga as
etapas no guia de iniciação.
Inclua as bibliotecas do kit de ML no seu Podfile:
pod 'Firebase/MLNLTranslate', '6.25.0'
Depois de instalar ou atualizar os pods do seu projeto, abra o projeto do Xcode
usando o .xcworkspace.
Importe o Firebase para seu app:
Swift
importFirebase
Objective-C
@importFirebase;
Traduzir uma string de texto
Para traduzir uma string entre dois idiomas, siga estas etapas:
Crie um objeto Translator, configurando-o com os idiomas de origem e de destino:
Swift
// Create an English-German translator:letoptions=TranslatorOptions(sourceLanguage:.en,targetLanguage:.de)letenglishGermanTranslator=NaturalLanguage.naturalLanguage().translator(options:options)
Objective-C
// Create an English-German translator:FIRTranslatorOptions*options=[[FIRTranslatorOptionsalloc]initWithSourceLanguage:FIRTranslateLanguageENtargetLanguage:FIRTranslateLanguageDE];FIRTranslator*englishGermanTranslator=[[FIRNaturalLanguagenaturalLanguage]translatorWithOptions:options];
Se você não souber o idioma do texto de entrada, use a API de identificação de idioma primeiro. Porém, certifique-se de não manter muitos modelos de idioma no dispositivo ao mesmo tempo.
Verifique se o modelo de tradução necessário foi salvo no dispositivo.
Não chame translate(_:completion:) até verificar se o modelo está disponível.
Swift
letconditions=ModelDownloadConditions(allowsCellularAccess:false,allowsBackgroundDownloading:true)englishGermanTranslator.downloadModelIfNeeded(with:conditions){erroringuarderror==nilelse{return}// Model downloaded successfully. Okay to start translating.}
Objective-C
FIRModelDownloadConditions*conditions=[[FIRModelDownloadConditionsalloc]initWithAllowsCellularAccess:NOallowsBackgroundDownloading:YES];[englishGermanTranslatordownloadModelIfNeededWithConditions:conditionscompletion:^(NSError*_Nullableerror){if(error!=nil){return;}// Model downloaded successfully. Okay to start translating.}];
Os modelos de idiomas têm cerca de 30 MB, portanto, faça o download deles apenas quando necessário e usando Wi-Fi, a menos que o usuário tenha especificado o contrário. Além disso, exclua modelos desnecessários.
Consulte Gerenciar explicitamente modelos de tradução.
Depois de confirmar o download do modelo, transmita uma string de texto no idioma de origem para translate(_:completion:):
O Kit de ML traduz o texto para o idioma de destino configurado e transmite o texto traduzido para o gerenciador de conclusão.
Gerenciar explicitamente modelos de tradução
Quando a API de tradução é usada conforme descrito acima, o Kit de ML faz o download automático
de modelos de tradução específicos do idioma para o dispositivo, conforme necessário. Também
é possível gerenciar explicitamente os modelos de tradução que você quer disponibilizar no
dispositivo usando a API de gerenciamento de modelos de tradução do Kit de ML. Isso pode ser útil se você quiser fazer o download de modelos antecipadamente ou excluir modelos desnecessários do dispositivo.
Para receber os modelos de tradução armazenados no dispositivo:
// Delete the German model if it's on the device.letdeModel=TranslateRemoteModel.translateRemoteModel(language:.de)ModelManager.modelManager().deleteDownloadedModel(deModel){erroringuarderror==nilelse{return}// Model deleted.
}
Objective-C
// Delete the German model if it's on the device.FIRTranslateRemoteModel*deModel=[FIRTranslateRemoteModeltranslateRemoteModelWithLanguage:FIRTranslateLanguageDE];[[FIRModelManagermodelManager]deleteDownloadedModel:deModelcompletion:^(NSError*_Nullableerror){if(error!=nil){return;}// Model deleted.}];
Para fazer o download de um modelo:
Swift
// Download the French model.letfrModel=TranslateRemoteModel.translateRemoteModel(language:.fr)// Keep a reference to the download progress so you can check that the model// is available before you use it.progress=ModelManager.modelManager().download(frModel,conditions:ModelDownloadConditions(allowsCellularAccess:false,allowsBackgroundDownloading:true))
Se você quiser saber o status do download com NotificationCenter, registre observadores para firebaseMLModelDownloadDidSucceed e firebaseMLModelDownloadDidFail. Certifique-se de usar uma referência fraca para self no bloco de observadores, já que os downloads podem levar algum tempo, e o objeto de origem pode ser liberado quando o download for concluído. Exemplo:
NotificationCenter.default.addObserver(forName:.firebaseMLModelDownloadDidSucceed,object:nil,queue:nil){[weakself]notificationinguardletstrongSelf=self,letuserInfo=notification.userInfo,letmodel=userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]as?TranslateRemoteModel,model==frModelelse{return}// The model was downloaded and is available on the device}NotificationCenter.default.addObserver(forName:.firebaseMLModelDownloadDidFail,object:nil,queue:nil){[weakself]notificationinguardletstrongSelf=self,letuserInfo=notification.userInfo,letmodel=userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]as?TranslateRemoteModelelse{return}leterror=userInfo[ModelDownloadUserInfoKey.error.rawValue]// ...}
Objective-C
// Download the French model.FIRModelDownloadConditions*conditions=[[FIRModelDownloadConditionsalloc]initWithAllowsCellularAccess:NOallowsBackgroundDownloading:YES];FIRTranslateRemoteModel*frModel=[FIRTranslateRemoteModeltranslateRemoteModelWithLanguage:FIRTranslateLanguageFR];// Keep a reference to the download progress so you can check that the model// is available before you use it.self.downloadProgress=[[FIRModelManagermodelManager]downloadModel:frModelconditions:conditions];
Se você quiser saber o status do download com NSNotificationCenter, registre observadores para FIRModelDownloadDidSucceedNotification e FIRModelDownloadDidFailNotification. Certifique-se de usar uma referência fraca para self no bloco de observadores, já que os downloads podem demorar algum tempo e o objeto de origem poderá ser liberado quando o download for concluído.
__blockMyViewController*weakSelf=self;[NSNotificationCenter.defaultCenteraddObserverForName:FIRModelDownloadDidSucceedNotificationobject:nilqueue:nilusingBlock:^(NSNotification*_Nonnullnote){if(weakSelf==nil|note.userInfo==nil){return;}FIRTranslateRemoteModel*model=note.userInfo[FIRModelDownloadUserInfoKeyRemoteModel];if([modelisKindOfClass:[FIRTranslateRemoteModelclass]] && model==frModel){// The model was downloaded and is available on the device}}];[NSNotificationCenter.defaultCenteraddObserverForName:FIRModelDownloadDidFailNotificationobject:nilqueue:nilusingBlock:^(NSNotification*_Nonnullnote){if(weakSelf==nil|note.userInfo==nil){return;}NSError*error=note.userInfo[FIRModelDownloadUserInfoKeyError];}];
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Não contém as informações de que eu preciso","missingTheInformationINeed","thumb-down"],["Muito complicado / etapas demais","tooComplicatedTooManySteps","thumb-down"],["Desatualizado","outOfDate","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Problema com as amostras / o código","samplesCodeIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-12 UTC."],[],[],null,["You can use ML Kit to translate text between languages. ML Kit\ncurrently supports translation between\n[59 languages](/docs/ml-kit/translation-language-support).\n\n\u003cbr /\u003e\n\nBefore you begin\n\n\u003cbr /\u003e\n\n1. If you have not already added Firebase to your app, do so by following the steps in the [getting started guide](/docs/ios/setup).\n2. Include the ML Kit libraries in your Podfile: \n\n ```\n pod 'Firebase/MLNLTranslate', '6.25.0'\n ```\n After you install or update your project's Pods, be sure to open your Xcode project using its `.xcworkspace`.\n3. In your app, import Firebase: \n\n Swift \n\n ```swift\n import Firebase\n ```\n\n Objective-C \n\n ```objective-c\n @import Firebase;\n ```\n\nTranslate a string of text\n\nTo translate a string between two languages:\n\n1. Create a `Translator` object, configuring it with the source and target\n languages:\n\n Swift \n\n // Create an English-German translator:\n let options = TranslatorOptions(sourceLanguage: .en, targetLanguage: .de)\n let englishGermanTranslator = NaturalLanguage.naturalLanguage().translator(options: options)\n\n Objective-C \n\n // Create an English-German translator:\n FIRTranslatorOptions *options =\n [[FIRTranslatorOptions alloc] initWithSourceLanguage:FIRTranslateLanguageEN\n targetLanguage:FIRTranslateLanguageDE];\n FIRTranslator *englishGermanTranslator =\n [[FIRNaturalLanguage naturalLanguage] translatorWithOptions:options];\n\n If you don't know the language of the input text, you can use the [language\n identification API](/docs/ml-kit/identify-languages) first. (But be sure you\n don't keep too many language models on the device at once.)\n2. Make sure the required translation model has been downloaded to the device.\n Don't call `translate(_:completion:)` until you know the model is available.\n\n Swift \n\n let conditions = ModelDownloadConditions(\n allowsCellularAccess: false,\n allowsBackgroundDownloading: true\n )\n englishGermanTranslator.downloadModelIfNeeded(with: conditions) { error in\n guard error == nil else { return }\n\n // Model downloaded successfully. Okay to start translating.\n }\n\n Objective-C \n\n FIRModelDownloadConditions *conditions =\n [[FIRModelDownloadConditions alloc] initWithAllowsCellularAccess:NO\n allowsBackgroundDownloading:YES];\n [englishGermanTranslator downloadModelIfNeededWithConditions:conditions\n completion:^(NSError *_Nullable error) {\n if (error != nil) {\n return;\n }\n // Model downloaded successfully. Okay to start translating.\n }];\n\n Language models are around 30MB, so don't download them unnecessarily, and\n only download them using WiFi, unless the user has specified otherwise. You\n should also delete unneeded models.\n See [Explicitly manage translation models](#manage_models).\n3. After you confirm the model has been downloaded, pass a string of text in\n the source language to `translate(_:completion:)`:\n\n Swift \n\n englishGermanTranslator.translate(text) { translatedText, error in\n guard error == nil, let translatedText = translatedText else { return }\n\n // Translation succeeded.\n }\n\n Objective-C \n\n [englishGermanTranslator translateText:text\n completion:^(NSString *_Nullable translatedText,\n NSError *_Nullable error) {\n if (error != nil || translatedText == nil) {\n return;\n }\n\n // Translation succeeded.\n }];\n\n ML Kit translates the text to the target language you configured and\n passes the translated text to the completion handler.\n\nExplicitly manage translation models\n\n\nWhen you use the translation API as described above, ML Kit automatically\ndownloads language-specific translation models to the device as required. You\ncan also explicitly manage the translation models you want available on the\ndevice by using ML Kit's translation model management API. This can be\nuseful if you want to download models ahead of time, or delete unneeded models\nfrom the device.\n\n\u003cbr /\u003e\n\nTo get the translation models stored on the device: \n\nSwift \n\n let localModels = ModelManager.modelManager().downloadedTranslateModels\n\nObjective-C \n\n NSSet\u003cFIRTranslateRemoteModel *\u003e *localModels =\n [FIRModelManager modelManager].downloadedTranslateModels;\n\nTo delete a model: \n\nSwift \n\n // Delete the German model if it's on the device.\n let deModel = TranslateRemoteModel.translateRemoteModel(language: .de)\n ModelManager.modelManager().deleteDownloadedModel(deModel) { error in\n guard error == nil else { return }\n // Model deleted.\n }\n\nObjective-C \n\n // Delete the German model if it's on the device.\n FIRTranslateRemoteModel *deModel =\n [FIRTranslateRemoteModel translateRemoteModelWithLanguage:FIRTranslateLanguageDE];\n [[FIRModelManager modelManager] deleteDownloadedModel:deModel\n completion:^(NSError * _Nullable error) {\n if (error != nil) {\n return;\n }\n // Model deleted.\n }];\n\nTo download a model: \n\nSwift \n\n // Download the French model.\n let frModel = TranslateRemoteModel.translateRemoteModel(language: .fr)\n\n // Keep a reference to the download progress so you can check that the model\n // is available before you use it.\n progress = ModelManager.modelManager().download(\n frModel,\n conditions: ModelDownloadConditions(\n allowsCellularAccess: false,\n allowsBackgroundDownloading: true\n )\n )\n\nIf you want to get the download status with `NotificationCenter`, register\nobservers for `firebaseMLModelDownloadDidSucceed` and\n`firebaseMLModelDownloadDidFail`. Be sure to use a weak reference to `self`\nin the observer block, since downloads can take some time, and the originating\nobject can be freed by the time the download finishes. For example: \n\n NotificationCenter.default.addObserver(\n forName: .firebaseMLModelDownloadDidSucceed,\n object: nil,\n queue: nil\n ) { [weak self] notification in\n guard let strongSelf = self,\n let userInfo = notification.userInfo,\n let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]\n as? TranslateRemoteModel,\n model == frModel\n else { return }\n // The model was downloaded and is available on the device\n }\n\n NotificationCenter.default.addObserver(\n forName: .firebaseMLModelDownloadDidFail,\n object: nil,\n queue: nil\n ) { [weak self] notification in\n guard let strongSelf = self,\n let userInfo = notification.userInfo,\n let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]\n as? TranslateRemoteModel\n else { return }\n let error = userInfo[ModelDownloadUserInfoKey.error.rawValue]\n // ...\n }\n\nObjective-C \n\n // Download the French model.\n FIRModelDownloadConditions *conditions =\n [[FIRModelDownloadConditions alloc] initWithAllowsCellularAccess:NO\n allowsBackgroundDownloading:YES];\n FIRTranslateRemoteModel *frModel =\n [FIRTranslateRemoteModel translateRemoteModelWithLanguage:FIRTranslateLanguageFR];\n\n // Keep a reference to the download progress so you can check that the model\n // is available before you use it.\n self.downloadProgress = [[FIRModelManager modelManager] downloadModel:frModel\n conditions:conditions];\n\nIf you want to get the download status with `NSNotificationCenter`, register\nobservers for `FIRModelDownloadDidSucceedNotification` and\n`FIRModelDownloadDidFailNotification`. Be sure to use a weak reference to\n`self` in the observer block, since downloads can take some time, and the\noriginating object can be freed by the time the download finishes. \n\n __block MyViewController *weakSelf = self;\n\n [NSNotificationCenter.defaultCenter\n addObserverForName:FIRModelDownloadDidSucceedNotification\n object:nil\n queue:nil\n usingBlock:^(NSNotification * _Nonnull note) {\n if (weakSelf == nil | note.userInfo == nil) {\n return;\n }\n\n FIRTranslateRemoteModel *model = note.userInfo[FIRModelDownloadUserInfoKeyRemoteModel];\n if ([model isKindOfClass:[FIRTranslateRemoteModel class]]\n && model == frModel) {\n // The model was downloaded and is available on the device\n }\n }];\n\n [NSNotificationCenter.defaultCenter\n addObserverForName:FIRModelDownloadDidFailNotification\n object:nil\n queue:nil\n usingBlock:^(NSNotification * _Nonnull note) {\n if (weakSelf == nil | note.userInfo == nil) {\n return;\n }\n\n NSError *error = note.userInfo[FIRModelDownloadUserInfoKeyError];\n }];"]]