在 iOS 系统中使用机器学习套件翻译文本
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
您可以使用机器学习套件实现语言之间的文本互译。机器学习套件目前支持 59 种语言之间的互译。
准备工作
- 如果您尚未将 Firebase 添加到自己的应用中,请按照入门指南中的步骤执行此操作。
- 在 Podfile 中添加机器学习套件库:
pod 'Firebase/MLNLTranslate', '6.25.0'
安装或更新项目的 Pod 之后,请务必使用 Xcode 项目的 .xcworkspace
来打开项目。
- 在您的应用中导入 Firebase:
Objective-C
@import Firebase;
翻译文本字符串
为实现字符串在两种语言之间的互译,请执行以下操作:
创建一个 Translator
对象,并使用源语言和目标语言对其进行配置:
Swift
// Create an English-German translator:
let options = TranslatorOptions(sourceLanguage: .en, targetLanguage: .de)
let englishGermanTranslator = NaturalLanguage.naturalLanguage().translator(options: options)
Objective-C
// Create an English-German translator:
FIRTranslatorOptions *options =
[[FIRTranslatorOptions alloc] initWithSourceLanguage:FIRTranslateLanguageEN
targetLanguage:FIRTranslateLanguageDE];
FIRTranslator *englishGermanTranslator =
[[FIRNaturalLanguage naturalLanguage] translatorWithOptions:options];
如果您不知道输入文本的语言,可以先使用语言识别 API。(但请确保您不会在设备上同时保留太多语言模型。)
确保已将所需的翻译模型下载到设备上。
确信模型可用之后,再调用 translate(_:completion:)
。
Swift
let conditions = ModelDownloadConditions(
allowsCellularAccess: false,
allowsBackgroundDownloading: true
)
englishGermanTranslator.downloadModelIfNeeded(with: conditions) { error in
guard error == nil else { return }
// Model downloaded successfully. Okay to start translating.
}
Objective-C
FIRModelDownloadConditions *conditions =
[[FIRModelDownloadConditions alloc] initWithAllowsCellularAccess:NO
allowsBackgroundDownloading:YES];
[englishGermanTranslator downloadModelIfNeededWithConditions:conditions
completion:^(NSError *_Nullable error) {
if (error != nil) {
return;
}
// Model downloaded successfully. Okay to start translating.
}];
语言模型大小约为 30 MB,因此若非必要,请勿下载。此外,除非用户另行指定,否则应仅使用 WiFi 下载语言模型。您还应删除不需要的模型。
请参阅显式管理翻译模型。
确认模型已下载后,将源语言的文本字符串传递至 translate(_:completion:)
:
Swift
englishGermanTranslator.translate(text) { translatedText, error in
guard error == nil, let translatedText = translatedText else { return }
// Translation succeeded.
}
Objective-C
[englishGermanTranslator translateText:text
completion:^(NSString *_Nullable translatedText,
NSError *_Nullable error) {
if (error != nil || translatedText == nil) {
return;
}
// Translation succeeded.
}];
机器学习套件将文本翻译为您配置的目标语言,然后将译文传递至完成处理程序。
显式管理翻译模型
在您按上文所述使用翻译 API 时,机器学习套件会根据需要自动将特定语言的翻译模型下载到设备。您还可以使用机器学习套件的翻译模型管理 API 来显式管理设备上可用的翻译模型。如果您想提前下载模型或从设备中删除不需要的模型,此方法会非常有用。
如需获取设备上存储的翻译模型,请运行以下代码:
Swift
let localModels = ModelManager.modelManager().downloadedTranslateModels
Objective-C
NSSet<FIRTranslateRemoteModel *> *localModels =
[FIRModelManager modelManager].downloadedTranslateModels;
如需删除模型,请运行以下代码:
Swift
// Delete the German model if it's on the device.
let deModel = TranslateRemoteModel.translateRemoteModel(language: .de)
ModelManager.modelManager().deleteDownloadedModel(deModel) { error in
guard error == nil else { return }
// Model deleted
.
}
Objective-C
// Delete the German model if it's on the device.
FIRTranslateRemoteModel *deModel =
[FIRTranslateRemoteModel translateRemoteModelWithLanguage:FIRTranslateLanguageDE];
[[FIRModelManager modelManager] deleteDownloadedModel:deModel
completion:^(NSError * _Nullable error) {
if (error != nil) {
return;
}
// Model deleted.
}];
如需下载模型,请运行以下代码:
Swift
// Download the French model.
let frModel = 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
)
)
如果您想通过 NotificationCenter
获取下载状态,请注册 firebaseMLModelDownloadDidSucceed
和 firebaseMLModelDownloadDidFail
的观察者。请务必在观察者块中使用对 self
的弱引用,因为下载可能需要一些时间,并且源对象可能到下载完成才会被释放。例如:
NotificationCenter.default.addObserver(
forName: .firebaseMLModelDownloadDidSucceed,
object: nil,
queue: nil
) { [weak self] notification in
guard let strongSelf = self,
let userInfo = notification.userInfo,
let model = 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
) { [weak self] notification in
guard let strongSelf = self,
let userInfo = notification.userInfo,
let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
as? TranslateRemoteModel
else { return }
let error = userInfo[ModelDownloadUserInfoKey.error.rawValue]
// ...
}
Objective-C
// Download the French model.
FIRModelDownloadConditions *conditions =
[[FIRModelDownloadConditions alloc] initWithAllowsCellularAccess:NO
allowsBackgroundDownloading:YES];
FIRTranslateRemoteModel *frModel =
[FIRTranslateRemoteModel translateRemoteModelWithLanguage:FIRTranslateLanguageFR];
// Keep a reference to the download progress so you can check that the model
// is available before you use it.
self.downloadProgress = [[FIRModelManager modelManager] downloadModel:frModel
conditions:conditions];
如果您想通过 NSNotificationCenter
获取下载状态,请注册 FIRModelDownloadDidSucceedNotification
和 FIRModelDownloadDidFailNotification
的观察者。请务必在观察者块中使用对 self
的弱引用,因为下载可能需要一些时间,并且源对象可能到下载完成才会被释放。
__block MyViewController *weakSelf = self;
[NSNotificationCenter.defaultCenter
addObserverForName:FIRModelDownloadDidSucceedNotification
object:nil
queue:nil
usingBlock:^(NSNotification * _Nonnull note) {
if (weakSelf == nil | note.userInfo == nil) {
return;
}
FIRTranslateRemoteModel *model = note.userInfo[FIRModelDownloadUserInfoKeyRemoteModel];
if ([model isKindOfClass:[FIRTranslateRemoteModel class]]
&& model == frModel) {
// The model was downloaded and is available on the device
}
}];
[NSNotificationCenter.defaultCenter
addObserverForName:FIRModelDownloadDidFailNotification
object:nil
queue:nil
usingBlock:^(NSNotification * _Nonnull note) {
if (weakSelf == nil | note.userInfo == nil) {
return;
}
NSError *error = note.userInfo[FIRModelDownloadUserInfoKeyError];
}];
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-12。
[null,null,["最后更新时间 (UTC):2025-08-12。"],[],[],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 }];"]]