diff --git a/README.md b/README.md index 05fffec..7ffb926 100644 --- a/README.md +++ b/README.md @@ -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 | ❌ | ❌ | diff --git a/translate-text/ios/TranslateText.m b/translate-text/ios/TranslateText.m index 9acdd8a..6657cc2 100644 --- a/translate-text/ios/TranslateText.m +++ b/translate-text/ios/TranslateText.m @@ -2,15 +2,76 @@ #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"]; + + NSLog(@" text = %@",text); + + if (text == nil) { + reject(@"TEXT_TRANSLATE_FAILED", @"Text cannot be null", nil); + return; + } + + NSString *sourceLanguage = [optionsMap objectForKey:@"sourceLanguage"]; + NSString *targetLanguage = [optionsMap objectForKey:@"targetLanguage"]; + + NSLog(@" sourceLanguage = %@",sourceLanguage); + NSLog(@" targetLanguage = %@",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