获取我们在 Firebase 峰会上发布的所有信息,了解 Firebase 可如何帮助您加快应用开发速度并满怀信心地运行应用。了解详情

在 iOS 上使用机器学习套件翻译文本

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

您可以使用 ML Kit 在语言之间翻译文本。 ML Kit 目前支持59 种语言之间的翻译。

在你开始之前

  1. 如果您尚未将 Firebase 添加到您的应用,请按照入门指南中的步骤进行操作。
  2. 在您的 Podfile 中包含 ML Kit 库:
    pod 'Firebase/MLNLTranslate', '6.25.0'
    
    安装或更新项目的 Pod 后,请务必使用其.xcworkspace打开您的 Xcode 项目。
  3. 在您的应用中,导入 Firebase:

    迅速

    import Firebase

    Objective-C

    @import Firebase;

翻译一串文本

要在两种语言之间翻译字符串:

  1. 创建一个Translator对象,使用源语言和目标语言对其进行配置:

    迅速

    // 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 。 (但请确保不要一次在设备上保留太多语言模型。)

  2. 确保所需的翻译模型已下载到设备。在您知道模型可用之前,不要调用translate(_:completion:)

    迅速

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

    语言模型大约 30MB,所以不要不必要地下载它们,只使用 WiFi 下载它们,除非用户另有说明。您还应该删除不需要的模型。请参阅显式管理翻译模型

  3. 确认模型已下载后,将源语言中的文本字符串传递给translate(_:completion:)

    迅速

    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 明确管理您希望在设备上可用的翻译模型。如果您想提前下载模型或从设备中删除不需要的模型,这会很有用。

要获取存储在设备上的翻译模型:

迅速

let localModels = ModelManager.modelManager().downloadedTranslateModels

Objective-C

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

要删除模型:

迅速

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

要下载模型:

迅速

// 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获取下载状态,请为firebaseMLModelDownloadDidSucceedfirebaseMLModelDownloadDidFail注册观察者。确保在观察者块中使用对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获取下载状态,请为FIRModelDownloadDidSucceedNotificationFIRModelDownloadDidFailNotification注册观察者。确保在观察者块中使用对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];
 }];