在 iOS 上使用 ML Kit 翻譯文字

你可以使用 ML Kit 翻譯不同語言的文字。機器學習套件 可以在超過 90 個 50 種語言

立即試用

事前準備

  1. 在 Podfile 中加入下列 ML Kit Pod:
    pod 'GoogleMLKit/Translate', '3.2.0'
    
  2. 安裝或更新專案的 Pod 後,請使用 .xcworkspace。Xcode 12.4 以上版本支援 ML Kit。

翻譯一段文字

如何在兩種語言之間翻譯字串:

  1. 建立 Translator 物件,並使用來源和目標設定該物件 語言:

    Swift

        // Create an English-German translator:
        let options = TranslatorOptions(sourceLanguage: .english, targetLanguage: .german)
        let englishGermanTranslator = Translator.translator(options: options)

    Objective-C

        // Create an English-German translator:
        MLKTranslatorOptions *options =
            [[MLKTranslatorOptions alloc] initWithSourceLanguage:MLKTranslateLanguageEnglish
                                                  targetLanguage:MLKTranslateLanguageGerman];
        MLKTranslator *englishGermanTranslator =
            [MLKTranslator translatorwithOptions:options];

    如果您不知道輸入文字的語言,可以使用語言 識別 API 會提供語言標記然後將語言標記轉換為 ML Kit 列舉項目程式碼取決於您使用的語言:

    請避免同時在裝置上保留過多語言模型,

  2. 確認所需翻譯模型已下載到裝置。 確認模型可用前,請勿呼叫 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

    MLKModelDownloadConditions *conditions =
        [[MLKModelDownloadConditions 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 下載下載。個人中心 不再需要模型 請參閱「明確管理翻譯模型」。

  3. 確認下載模型後,請在 將原文語言轉換為 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 會將文字翻譯成您設定的目標語言 將翻譯的文字傳遞至完成處理常式。

譯者的生命週期是由 ARC (自動參照計算) 控管, 這是 iOS 開發作業的建議慣例開發人員可以遵守 移除所有高度的參考檔案後,譯者即可取消配置。

譯者在記憶體中載入時,可以佔用 30 MB 至 150 MB 的空間。開發人員 建立並行專案時,請務必考量裝置/應用程式的記憶體預算 避免在裝置上保留過多語言模型 一起使用

明確管理翻譯模型

按照上述方式使用翻譯 API 時,ML Kit 會自動使用 視需要下載特定語言專屬的翻譯模型至裝置。個人中心 也可以明確管理 整合了 ML Kit 的翻譯模型管理 API可用的值包括 舉例來說,如果您想事先下載模型,或是刪除不需要的模型 登入裝置。

如要取得儲存在裝置上的翻譯模型:

Swift

let localModels = ModelManager.modelManager().downloadedTranslateModels

Objective-C

NSSet *localModels =
    [MLKModelManager modelManager].downloadedTranslateModels;

如要刪除模型:

Swift

// Delete the German model if it's on the device.
let germanModel = TranslateRemoteModel.translateRemoteModel(language: .german)
ModelManager.modelManager().deleteDownloadedModel(germanModel) { error in
    guard error == nil else { return }
    // Model deleted.
}

Objective-C

// Delete the German model if it's on the device.
MLKTranslateRemoteModel *germanModel =
    [MLKTranslateRemoteModel translateRemoteModelWithLanguage:MLKTranslateLanguageGerman];
[[MLKModelManager modelManager] deleteDownloadedModel:germanModel
                                           completion:^(NSError * _Nullable error) {
                                               if (error != nil) {
                                                   return;
                                               }
                                               // Model deleted.

如何下載模型:

Swift

// Download the French model.
let frenchModel = TranslateRemoteModel.translateRemoteModel(language: .french)

// Keep a reference to the download progress so you can check that the model
// is available before you use it.
progress = ModelManager.modelManager().download(
    frenchModel,
    conditions: ModelDownloadConditions(
        allowsCellularAccess: false,
        allowsBackgroundDownloading: true
    )
)

如要向「NotificationCenter」取得下載狀態,請註冊 mlkitModelDownloadDidSucceedmlkitModelDownloadDidFail。請務必對「self」使用較弱的參照 ,因為下載可能需要一些時間,而且 物件即可釋出。例如:

NotificationCenter.default.addObserver(
    forName: .mlkitModelDownloadDidSucceed,
    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 == frenchModel
        else { return }
    // The model was downloaded and is available on the device
}

NotificationCenter.default.addObserver(
    forName: .mlkitModelDownloadDidFail,
    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.
MLKModelDownloadConditions *conditions =
    [[MLKModelDownloadConditions alloc] initWithAllowsCellularAccess:NO
                                         allowsBackgroundDownloading:YES];
MLKTranslateRemoteModel *frenchModel =
    [MLKTranslateRemoteModel translateRemoteModelWithLanguage:MLKTranslateLanguageFrench];

// Keep a reference to the download progress so you can check that the model
// is available before you use it.
self.downloadProgress = [[MLKModelManager modelManager] downloadModel:frenchModel
conditions:conditions];

如要向「NSNotificationCenter」取得下載狀態,請註冊 MLKModelDownloadDidSucceedNotificationMLKModelDownloadDidFailNotification。請務必使用弱式參照 觀察器區塊中的 self,因為下載可能需要一些時間, 可在下載完成後釋放。

__block MyViewController *weakSelf = self;

[NSNotificationCenter.defaultCenter
 addObserverForName:MLKModelDownloadDidSucceedNotification
 object:nil
 queue:nil
 usingBlock:^(NSNotification * _Nonnull note) {
     if (weakSelf == nil | note.userInfo == nil) {
         return;
     }

     MLKTranslateRemoteModel *model = note.userInfo[MLKModelDownloadUserInfoKeyRemoteModel];
     if ([model isKindOfClass:[MLKTranslateRemoteModel class]]
         && model == frenchModel) {
         // The model was downloaded and is available on the device
     }
 }];

[NSNotificationCenter.defaultCenter
 addObserverForName:MLKModelDownloadDidFailNotification
 object:nil
 queue:nil
 usingBlock:^(NSNotification * _Nonnull note) {
     if (weakSelf == nil | note.userInfo == nil) {
         return;
     }

     NSError *error = note.userInfo[MLKModelDownloadUserInfoKeyError];
 }];