Translate text with ML Kit on iOS

You can use ML Kit to translate text between languages. ML Kit currently supports translation between 59 languages.

Before you begin

  1. If you have not already added Firebase to your app, do so by following the steps in the getting started guide.
  2. Include the ML Kit libraries in your Podfile:
     pod 'Firebase/MLNLTranslate', '6.25.0' 
    After you install or update your project's Pods, be sure to open your Xcode project using its .xcworkspace.
  3. In your app, import Firebase:

    Swift

    importFirebase

    Objective-C

    @importFirebase;

Translate a string of text

To translate a string between two languages:

  1. Create a Translator object, configuring it with the source and target languages:

    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];

    If you don't know the language of the input text, you can use the language identification API first. (But be sure you don't keep too many language models on the device at once.)

  2. Make sure the required translation model has been downloaded to the device. Don't call translate(_:completion:) until you know the model is available.

    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.}];

    Language models are around 30MB, so don't download them unnecessarily, and only download them using WiFi, unless the user has specified otherwise. You should also delete unneeded models. See Explicitly manage translation models.

  3. After you confirm the model has been downloaded, pass a string of text in the source language to translate(_:completion:):

    Swift

    englishGermanTranslator.translate(text){translatedText,erroringuarderror==nil,lettranslatedText=translatedTextelse{return}// Translation succeeded.}

    Objective-C

    [englishGermanTranslatortranslateText:textcompletion:^(NSString*_NullabletranslatedText,NSError*_Nullableerror){if(error!=nil||translatedText==nil){return;}// Translation succeeded.}];

    ML Kit translates the text to the target language you configured and passes the translated text to the completion handler.

Explicitly manage translation models

When you use the translation API as described above, ML Kit automatically downloads language-specific translation models to the device as required. You can also explicitly manage the translation models you want available on the device by using ML Kit's translation model management API. This can be useful if you want to download models ahead of time, or delete unneeded models from the device.

To get the translation models stored on the device:

Swift

letlocalModels=ModelManager.modelManager().downloadedTranslateModels

Objective-C

NSSet<FIRTranslateRemoteModel*>*localModels=[FIRModelManagermodelManager].downloadedTranslateModels;

To delete a model:

Swift

// 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.}];

To download a model:

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))

If you want to get the download status with NotificationCenter, register observers for firebaseMLModelDownloadDidSucceed and firebaseMLModelDownloadDidFail. Be sure to use a weak reference to self in the observer block, since downloads can take some time, and the originating object can be freed by the time the download finishes. For example:

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];

If you want to get the download status with NSNotificationCenter, register observers for FIRModelDownloadDidSucceedNotification and FIRModelDownloadDidFailNotification. Be sure to use a weak reference to self in the observer block, since downloads can take some time, and the originating object can be freed by the time the download finishes.

__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];}];