你可以使用 ML Kit 翻譯不同語言的文字。ML Kit 目前支援 59 種語言的互譯功能。
事前準備
- 如果您尚未將 Firebase 加入應用程式,請按照入門指南中的步驟進行。
- 在 Podfile 中加入 ML Kit 程式庫:
pod 'Firebase/MLNLTranslate', '6.25.0'
安裝或更新專案的 Pod 後,請務必使用.xcworkspace
開啟 Xcode 專案。 - 在應用程式中匯入 Firebase:
Swift
import 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,因此除非使用者另有指定,否則請避免不必要的下載,並只使用 Wi-Fi 下載。建議您一併刪除不需要的模型。請參閱「明確管理翻譯模型」。
確認下載模型後,請將原文語言的字串傳送至
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. }];
ML Kit 會將文字轉譯成您設定的目標語言,並將翻譯後的文字傳送給完成處理常式。
明確管理翻譯模型
按照上述方式使用翻譯 API 時,ML Kit 會視需要自動將特定語言的翻譯模型下載至裝置。您也可以使用 ML Kit 的翻譯模型管理 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];
}];