Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ React Native On-Device Machine Learning w/ Google ML Kit
| [Face Detection](./face-detection) | ✅ | ✅ |
| [Text Recognition](./text-recognition) | ✅ | ✅ |
| [Barcode Scanning](./barcode-scanning) | ✅ | ✅ |
| [Translate Text](./translate-text) | ✅ | |
| [Translate Text](./translate-text) | ✅ | |
| Object Detection and Tracking | ❌ | ❌ |
| Digital Ink Recognition | ❌ | ❌ |
| Smart Replies | ❌ | ❌ |
63 changes: 60 additions & 3 deletions translate-text/ios/TranslateText.m
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,72 @@

#import "TranslateText.h"

@import MLKitTranslate;
@import MLKitCommon;


@implementation TranslateText

RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(sampleMethod:(NSString *)stringArgument numberParameter:(nonnull NSNumber *)numberArgument callback:(RCTResponseSenderBlock)callback)
RCT_EXPORT_METHOD(translate:(NSDictionary *)optionsMap
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
// TODO: Implement some actually useful functionality
callback(@[[NSString stringWithFormat: @"numberArgument: %@ stringArgument: %@", numberArgument, stringArgument]]);
NSString *text = [optionsMap objectForKey:@"text"];

if (text == nil) {
reject(@"TEXT_TRANSLATE_FAILED", @"Text cannot be null", nil);
return;
}

NSString *sourceLanguage = [optionsMap objectForKey:@"sourceLanguage"];
NSString *targetLanguage = [optionsMap objectForKey:@"targetLanguage"];

if (sourceLanguage == nil) {
reject(@"TEXT_TRANSLATE_FAILED", @"Source language cannot be null", nil);
return;
}

if (targetLanguage == nil) {
reject(@"TEXT_TRANSLATE_FAILED", @"Target language cannot be null", nil);
return;
}

MLKTranslatorOptions *options = [[MLKTranslatorOptions alloc]
initWithSourceLanguage:sourceLanguage
targetLanguage:targetLanguage];

MLKTranslator *translator = [MLKTranslator
translatorWithOptions:options];

bool hasRequireWifi = [optionsMap objectForKey:@"requireWifi"];

MLKModelDownloadConditions *conditions = [[MLKModelDownloadConditions alloc]
initWithAllowsCellularAccess:!hasRequireWifi
allowsBackgroundDownloading:YES];

[translator
downloadModelIfNeededWithConditions:conditions
completion:^(NSError *_Nullable error) {

if (error != nil) {
reject(@"TEXT_TRANSLATE_FAILED", @"Error was found", error);
return;
}

[translator
translateText:text
completion:^(NSString *_Nullable translatedText, NSError *_Nullable error)
{
if (error != nil || translatedText == nil) {
reject(@"TEXT_TRANSLATE_FAILED", @"Error was found", error);
return;
}

resolve(translatedText);
}];
}];
}

@end