Translate text with ML Kit on iOS
Stay organized with collections
Save and categorize content based on your preferences.
You can use ML Kit to translate text between languages. ML Kit currently supports translation between 59 languages.
Before you begin
- If you have not already added Firebase to your app, do so by following the steps in the getting started guide.
- Include the ML Kit libraries in your Podfile:
After you install or update your project's Pods, be sure to open your Xcode project using itspod 'Firebase/MLNLTranslate', '6.25.0'
.xcworkspace. - In your app, import Firebase:
Swift
importFirebase
Objective-C
@importFirebase;
Translate a string of text
To translate a string between two languages:
Create a
Translatorobject, 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:FIRTranslateLanguageEN targetLanguage: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.)
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){errorin guarderror==nilelse{return} // Model downloaded successfully. Okay to start translating. }Objective-C
FIRModelDownloadConditions*conditions= [[FIRModelDownloadConditionsalloc]initWithAllowsCellularAccess:NO allowsBackgroundDownloading:YES]; [englishGermanTranslatordownloadModelIfNeededWithConditions:conditions completion:^(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.
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,errorin guarderror==nil,lettranslatedText=translatedTextelse{return} // Translation succeeded. }Objective-C
[englishGermanTranslatortranslateText:text completion:^(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){errorin
guarderror==nilelse{return}
// Model deleted.
}
Objective-C
// Delete the German model if it's on the device.
FIRTranslateRemoteModel*deModel=
[FIRTranslateRemoteModeltranslateRemoteModelWithLanguage:FIRTranslateLanguageDE];
[[FIRModelManagermodelManager]deleteDownloadedModel:deModel
completion:^(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]notificationin
guardletstrongSelf=self,
letuserInfo=notification.userInfo,
letmodel=userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
as?TranslateRemoteModel,
model==frModel
else{return}
// The model was downloaded and is available on the device
}
NotificationCenter.default.addObserver(
forName:.firebaseMLModelDownloadDidFail,
object:nil,
queue:nil
){[weakself]notificationin
guardletstrongSelf=self,
letuserInfo=notification.userInfo,
letmodel=userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
as?TranslateRemoteModel
else{return}
leterror=userInfo[ModelDownloadUserInfoKey.error.rawValue]
// ...
}
Objective-C
// Download the French model.
FIRModelDownloadConditions*conditions=
[[FIRModelDownloadConditionsalloc]initWithAllowsCellularAccess:NO
allowsBackgroundDownloading: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:frModel
conditions: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.defaultCenter
addObserverForName:FIRModelDownloadDidSucceedNotification
object:nil
queue:nil
usingBlock:^(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.defaultCenter
addObserverForName:FIRModelDownloadDidFailNotification
object:nil
queue:nil
usingBlock:^(NSNotification*_Nonnullnote){
if(weakSelf==nil|note.userInfo==nil){
return;
}
NSError*error=note.userInfo[FIRModelDownloadUserInfoKeyError];
}];