### Get Available Languages (Swift & Objective-C) Source: https://context7.com/applanga/sdk-ios/llms.txt Retrieve a list of all languages that are configured within your Applanga project. This is useful for populating language selection UIs. Ensure to update the SDK before fetching the list to get the latest data. ```swift // Swift: Get all available languages let languages = Applanga.availableLanguages() // Display in settings UI class LanguageSelectionViewController: UITableViewController { var languages: [String] = [] override func viewDidLoad() { super.viewDidLoad() // Update to sync latest language list from dashboard Applanga.update { success in if success { self.languages = Applanga.availableLanguages() self.tableView.reloadData() } } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return languages.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "LanguageCell", for: indexPath) cell.textLabel?.text = languages[indexPath.row] return cell } } ``` ```objc // Objective-C: Get all available languages NSArray *languages = [Applanga availableLanguages]; // Display languages for (NSString *language in languages) { NSLog(@"Available language: %@", language); } ``` -------------------------------- ### Asynchronous Applanga Calls in WKWebView (JavaScript) Source: https://context7.com/applanga/sdk-ios/llms.txt Demonstrates how to use Applanga's asynchronous JavaScript API within a WKWebView to fetch localized strings. This includes examples for `getString`, `getPluralString`, and `getQuantityString`, with callback functions to handle the translated content. Ensure Applanga's JavaScript bridge is correctly set up in the WebView. ```javascript // JavaScript: Asynchronous Applanga calls in WKWebView Applanga.getString('welcome_message', undefined, undefined, undefined, undefined, undefined, function(translation) { document.getElementById('title').innerText = translation; } ); Applanga.getString('greeting', 'John,25', ',', undefined, undefined, undefined, function(translation) { console.log(translation); } ); Applanga.getPluralString('items_count', 'one', undefined, undefined, function(translation) { console.log(translation); } ); Applanga.getQuantityString('items_count', 5, undefined, undefined, function(translation) { console.log(translation); } ); ``` -------------------------------- ### Disable Waiting on App Start for Applanga Updates Source: https://github.com/applanga/sdk-ios/blob/master/README.md By default, the Applanga SDK waits for initial string updates from the dashboard, potentially delaying app start. Setting `ApplangaWaitOnAppStart` to `false` allows the app to start immediately, but may result in outdated strings on initial screens. ```xml ... ApplangaWaitOnAppStart ... ``` -------------------------------- ### Add Applanga Framework Manually (iOS) Source: https://github.com/applanga/sdk-ios/blob/master/README.md Manual installation of the Applanga SDK by adding the framework to your Xcode project. Includes steps for modifying build settings and adding a run script phase for stripping the framework. ```bash bash "$BUILT_PRODUCTS_DIR/$FRAMEWORKS_FOLDER_PATH/Applanga.framework/strip-framework.sh" ``` -------------------------------- ### Install Applanga via CocoaPods Source: https://github.com/applanga/sdk-ios/blob/master/README.md Integrates the Applanga SDK into your iOS project using CocoaPods. Add 'Applanga' to your Podfile and run 'pod install'. For UITests, also include 'ApplangaUITest'. ```ruby pod 'Applanga' pod 'ApplangaUITest' # For UITests ``` -------------------------------- ### Update Applanga Settings File Automatically (Bash) Source: https://context7.com/applanga/sdk-ios/llms.txt This script should be added to Xcode Build Phases to automatically update the Applanga settings file during the build process. It supports CocoaPods, Swift Package Manager, and manual installations. Ensure the script path is correct for your installation method. ```bash # Add to Xcode Build Phases -> New Run Script Phase # For CocoaPods installation: bash "$SOURCE_ROOT/Pods/Applanga/Applanga.xcframework/update-settingsfile.sh" "$SOURCE_ROOT/$TARGET_NAME" # For Swift Package Manager installation: bash "${BUILD_DIR%Build/*}/SourcePackages/checkouts/sdk-ios/Applanga.xcframework/update-settingsfile.sh" "$SOURCE_ROOT/$TARGET_NAME" # For manual installation: bash "$BUILT_PRODUCTS_DIR/$FRAMEWORKS_FOLDER_PATH/Applanga.xcframework/update-settingsfile.sh" "$SOURCE_ROOT/$TARGET_NAME" # Manual command line update: # Navigate to Applanga.framework directory and run: # bash update-settingsfile.sh /path/to/your/project ``` -------------------------------- ### Get Translated Strings in UIWebView and WKWebView Source: https://github.com/applanga/sdk-ios/blob/master/README.md These code examples show how to retrieve translated strings using Applanga. The `UIWebView` version is synchronous, while the `WKWebView` version is asynchronous and includes a callback function to handle the translation result. Both use `Applanga.getString` with an `APPLANGA_ID`. ```javascript //UIWebView translation = Applanga.getString('APPLANGA_ID') //WKWebView Applanga.getString('APPLANGA_ID', undefined, undefined, undefined, undefined, undefined, function(translation) { }) ``` -------------------------------- ### Configure Automatic Tag Upload of Local Strings Source: https://github.com/applanga/sdk-ios/blob/master/README.md This setting enables the automatic upload of a tag containing all local strings in the app upon app start or debug runs, after `Applanga.update()`. The tag prefix is combined with the bundle version. This can be used with additional string files or frameworks. ```xml ... ApplangaTagLocalStringsPrefix some_tag ... ``` -------------------------------- ### Get Available Applanga Project Languages in iOS Source: https://github.com/applanga/sdk-ios/blob/master/README.md Provides code snippets to retrieve a list of available languages from an Applanga project. The function `Applanga.availableLanguages()` returns an array of ISO language codes. Ensure `Applanga.update()` is called before to sync the latest language list. ```objc //objc NSArray *languages = [Applanga availableLanguages]; ``` ```swift //swift let languages = Applanga.availableLanguages() ``` -------------------------------- ### Pluralization with Applanga SDK in Swift and Objective-C Source: https://context7.com/applanga/sdk-ios/llms.txt Demonstrates how to handle pluralization rules in Swift and Objective-C using the Applanga SDK. It covers pluralizing by quantity, where the SDK automatically determines the correct rule, and how to explicitly specify plural rules like 'one'. The code also shows how pluralized IDs should be structured in the Applanga dashboard. ```swift // Swift: Pluralize by quantity (SDK determines correct rule) let quantity = 5 let message = Applanga.localizedString(forKey: "items_count", withDefaultValue: "%d items", andArguments: nil, andPluralRule: ALPluralRuleForQuantity(quantity)) let formatted = NSString.localizedStringWithFormat(NSString(string: message), quantity) // Output: "5 items" (uses [other] rule for English) // Explicit plural rule let singleItem = Applanga.localizedString(forKey: "items_count", withDefaultValue: "one item", andArguments: nil, andPluralRule: ALPluralRule.one) // On Applanga dashboard, create pluralized IDs: // "items_count[zero]" = "no items" // "items_count[one]" = "%d item" // "items_count[two]" = "%d items" // "items_count[few]" = "%d items" // "items_count[many]" = "%d items" // "items_count[other]" = "%d items" ``` ```objectivec // Objective-C: Pluralize by quantity NSInteger quantity = 5; NSString *template = [Applanga localizedStringForKey:@"items_count" withDefaultValue:@"%d items" andArguments:nil andPluralRule:ALPluralRuleForQuantity(quantity)]; NSString *formatted = [NSString localizedStringWithFormat:template, quantity]; // Explicit plural rule NSString *singleItem = [Applanga localizedStringForKey:@"items_count" withDefaultValue:@"one item" andArguments:nil andPluralRule:ALPluralRuleOne]; ``` -------------------------------- ### Take Automated Screenshots with Applanga SDK in iOS Source: https://github.com/applanga/sdk-ios/blob/master/README.md Demonstrates how to capture screenshots with specific tags during UI tests using the Applanga SDK. This is useful for automated testing and localization previews. It requires the ApplangaUITest framework and an XCUIApplication instance. ```objc #import @interface MyUITestCase : XCTestCase @property ApplangaUITest *applangaUITest; @end @implementation MyUITestCase - (void)setUp { ... XCUIApplication* app = [[XCUIApplication alloc] init]; self.applangaUITest = [[ApplangaUITest alloc] initWithApp:app enableShowIdMode:false]; [app launch]; } - (void)testScreenshot { XCUIApplication *app = [[XCUIApplication alloc] init]; NSArray* expectations = [NSArray arrayWithObject:[self.applangaUITest takeScreenshotWithTag:@"ScreenName1"]]; [self waitForExpectations:expectations timeout:10]; //navigate to next view ... NSArray* expectations = [NSArray arrayWithObject:[self.applangaUITest takeScreenshotWithTag:@"ScreenName2"]]; [self waitForExpectations:expectations timeout:10]; } @end ``` ```swift import ApplangaUITest class AutomatedScreenshotsTest: XCTestCase { let app = XCUIApplication() var applangaUITest: ApplangaUITest? func testScreenshot() { // enable show id mode if you are using swift ui so the string id will be linked to the tag name correctly // after that repeat the screenshot without show id mode applangaUITest = ApplangaUITest(app: app, enableShowIdMode: false) app.launch() wait(for: [applangaUITest!.takeScreenshot(tag: "ScreenName")], timeout: 10.0) } } ``` -------------------------------- ### Initialize ApplangaUITest for Xcode (Swift) Source: https://github.com/applanga/sdk-ios/blob/master/README.md Initializes the `ApplangaUITest` class for use in Swift UITests within Xcode. It takes an `XCUIApplication` instance as input. ```swift //swift let app = XCUIApplication() let applangaUITest = ApplangaUITest(app: app) ``` -------------------------------- ### CocoaPods Configuration for Applanga SDK Source: https://context7.com/applanga/sdk-ios/llms.txt Integrates the Applanga SDK into your iOS project using CocoaPods. This Podfile configuration includes the main Applanga SDK for your app target and optionally for watchOS extensions, as well as the ApplangaUITest pod for UI testing screenshot support. Ensure your platform version and target names are correctly set. ```ruby # Podfile platform :ios, '12.0' target 'YourApp' do use_frameworks! # Main SDK pod 'Applanga' # For watchOS extension target target 'YourApp WatchKit Extension' do pod 'Applanga' end end target 'YourAppUITests' do use_frameworks! # UITest screenshot support pod 'ApplangaUITest' end # Install: # pod install # open YourApp.xcworkspace ``` -------------------------------- ### Applanga SDK Configuration via Info.plist (XML) Source: https://context7.com/applanga/sdk-ios/llms.txt Configure Applanga SDK behavior by adding specific keys to your application's Info.plist file. These settings control aspects like update groups, languages, draft mode, and string collection. ```xml ApplangaUpdateGroups tutorial,chapter1,chapter2 ApplangaUpdateLanguages en,de,fr,es-MX ApplangaInitialUpdate ApplangaDraftModeEnabled ApplangaTranslateWebViews ApplangaCollectStoryBoardStrings ApplangaAdditionalStringFiles CustomStrings,SettingsText ApplangaAdditionalFrameworks MyFramework,AnotherFramework ApplangaConvertPlaceholders ApplangaLanguageMap zh-Hant-HK=zh-HK,es-CL=es-MX ApplangaLanguageFallback system ApplangaCustomLanguageFallback es-MX es-MX es-US es en-US en-GB de-DE ApplangaWaitOnAppStart ApplangaTagLocalStringsPrefix release_tag ApplangaScreenshotUseSupportedLanguageFallback ``` -------------------------------- ### Swift Package Manager Configuration for Applanga SDK Source: https://context7.com/applanga/sdk-ios/llms.txt Integrates the Applanga SDK into your iOS project using Swift Package Manager. This configuration specifies the repository URL and the version constraint for the Applanga SDK. It also defines how the Applanga and ApplangaUITest libraries are linked to your application and test targets. ```swift // Package.swift import PackageDescription let package = Package( name: "YourApp", dependencies: [ .package(url: "https://github.com/applanga/sdk-ios", from: "2.0.218") ], targets: [ .target( name: "YourApp", dependencies: ["Applanga"]), .testTarget( name: "YourAppUITests", dependencies: ["ApplangaUITest"]) ] ) // In Xcode 12+: // 1. File -> Add Packages... // 2. Enter: https://github.com/applanga/sdk-ios // 3. Select latest release tag // 4. Add Applanga to app target // 5. Add ApplangaUITest to UITest target ``` -------------------------------- ### Enable Draft Mode for Screenshot Capture (XML & Swift) Source: https://context7.com/applanga/sdk-ios/llms.txt Configures and triggers Applanga's Draft Mode for manual screenshot capture. This involves enabling Draft Mode in the `Info.plist` file and using programmatic calls in Swift to show the draft mode dialog or present the screenshot menu. The process also involves a specific gesture within the app to initiate the capture. ```xml ApplangaDraftModeEnabled ``` ```swift // Swift: Trigger Draft Mode programmatically Applanga.showDraftModeDialog() // For tvOS: Present screenshot menu Applanga.setScreenShotMenuVisible(true) // Manual screenshot capture in Draft Mode: // 1. Enable Draft Mode on Applanga dashboard for your app // 2. In the app, make a two-finger swipe downward gesture // 3. Screenshot menu appears with list of tags from dashboard // 4. Select a tag and press "Capture Screenshot" // 5. Screenshot with string positions is uploaded to dashboard ``` -------------------------------- ### Initialize ApplangaUITest for Xcode (Objective-C) Source: https://github.com/applanga/sdk-ios/blob/master/README.md Initializes the `ApplangaUITest` class for use in Xcode UITests. It requires an `XCUIApplication` instance and an option to enable 'Show ID Mode'. ```objc //objc XCUIApplication* app = [[XCUIApplication alloc] init]; ApplangaUITest* applangaUITest = [[ApplangaUITest alloc] initWithApp:app enableShowIdMode:false]; ``` -------------------------------- ### Manual Applanga Settings File Update Command Line Source: https://github.com/applanga/sdk-ios/blob/master/README.md Execute the settings file update script manually from the command line. This is useful for testing or integrating into custom build processes outside of Xcode's Build Phases. ```bash bash update-settingsfile.sh ${YOUR TARGET DIRECTORY PATH} ``` -------------------------------- ### Update Content Programmatically with Applanga SDK in Swift and Objective-C Source: https://context7.com/applanga/sdk-ios/llms.txt Shows how to fetch the latest translations from Applanga servers at runtime without needing to restart the application. This includes updating all languages for the main group or specifying particular groups and languages for the update. The completion handler provides feedback on the success or failure of the update process. ```swift // Swift: Update all languages for main group Applanga.update { (success: Bool) in if success { print("Translations updated successfully") // Recreate UI to show new translations let storyboard = UIStoryboard(name: "Main", bundle: nil) if let rootVC = storyboard.instantiateInitialViewController() { UIApplication.shared.windows.first?.rootViewController = rootVC } } else { print("Translation update failed") } } // Update specific groups and languages let groups: [String] = ["onboarding", "settings", "premium"] let languages: [String] = ["en", "de", "fr", "es"] Applanga.updateGroups(groups, andLanguages: languages) { (success: Bool) in if success { print("Specific groups and languages updated") } } ``` ```objectivec // Objective-C: Update all languages for main group [Applanga updateWithCompletionHandler:^(BOOL success) { if (success) { NSLog(@"Translations updated successfully"); // Recreate UI to show new translations } else { NSLog(@"Translation update failed"); } }]; // Update specific groups and languages NSArray* groups = @[@"onboarding", @"settings", @"premium"]; NSArray* languages = @[@"en", @"de", @"fr", @"es"]; [Applanga updateGroups:groups andLanguages:languages withCompletionHandler:^(BOOL success) { if (success) { NSLog(@"Specific groups and languages updated"); } }]; ``` -------------------------------- ### SwiftUI Integration with Text Extensions (Swift) Source: https://context7.com/applanga/sdk-ios/llms.txt Integrates Applanga localization into SwiftUI views by defining custom `Text` initializers. These extensions leverage `NSLocalizedString` to fetch localized strings based on provided keys and default values. The code also shows how to use these extensions in a `ContentView` and how to manage language selection in a `LanguagePickerView`. ```swift // Swift: SwiftUI Text extension for Applanga import SwiftUI extension Text { init(applangaKey: String) { self.init(NSLocalizedString(applangaKey, tableName: nil, bundle: Bundle.main, value: "", comment: "")) } init(applangaKey: String, defaultValue: String) { self.init(NSLocalizedString(applangaKey, tableName: nil, bundle: Bundle.main, value: defaultValue, comment: "")) } } // Usage in SwiftUI views struct ContentView: View { var body: some View { VStack { Text(applangaKey: "welcome_title", defaultValue: "Welcome") .font(.largeTitle) Text(applangaKey: "app_description", defaultValue: "This is the app description") .font(.body) Button(action: { Applanga.update { success in print("Update: \(success)") } }) { Text(applangaKey: "update_button", defaultValue: "Update Translations") } } } } struct LanguagePickerView: View { @State private var selectedLanguage = "en" @State private var languages: [String] = [] var body: some View { List(languages, id: \.self) { language in Button(language) { Applanga.setLanguage(language) selectedLanguage = language } } .onAppear { languages = Applanga.availableLanguages() } } } ``` -------------------------------- ### Configure Applanga Settings File Source: https://github.com/applanga/sdk-ios/blob/master/README.md Instructions for configuring the Applanga SDK by adding a settings file to your app's resources. The SDK automatically loads this file upon initialization. ```text Add the Applanga Settings File to your app's resources. ``` -------------------------------- ### Configure InfoPlist for Applanga Screenshot Fallback Source: https://github.com/applanga/sdk-ios/blob/master/README.md This XML snippet shows how to configure the Info.plist file to enable fallback to the supported language for screenshots when using Applanga. This ensures that screenshots are displayed using a supported language when the primary language is not available. ```xml ApplangaScreenshotUseSupportedLanguageFallback ``` -------------------------------- ### Automated Screenshot Capture in UITests (Swift/Objective-C) Source: https://context7.com/applanga/sdk-ios/llms.txt Automate screenshot capture during UITest execution using ApplangaUITest. This functionality allows for capturing screenshots with or without string ID detection, useful for localization testing and workflow automation. It requires the ApplangaUITest framework. ```swift // Swift: Automated screenshot capture in UITests import XCTest import ApplangaUITest class AutomatedScreenshotsTest: XCTestCase { let app = XCUIApplication() var applangaUITest: ApplangaUITest? override func setUp() { super.setUp() continueAfterFailure = false // Initialize with showIdMode disabled for normal screenshots applangaUITest = ApplangaUITest(app: app, enableShowIdMode: false) app.launch() } func testCaptureAllScreens() { // Home screen wait(for: [applangaUITest!.takeScreenshot(tag: "HomeScreen")], timeout: 10.0) // Navigate to settings app.buttons["Settings"].tap() wait(for: [applangaUITest!.takeScreenshot(tag: "SettingsScreen")], timeout: 10.0) // Navigate to profile app.buttons["Profile"].tap() wait(for: [applangaUITest!.takeScreenshot(tag: "ProfileScreen")], timeout: 10.0) } // For SwiftUI: Capture with showIdMode first, then without func testSwiftUIScreenshots() { // First pass: with showIdMode to link string IDs applangaUITest = ApplangaUITest(app: app, enableShowIdMode: true) app.launch() wait(for: [applangaUITest!.takeScreenshot(tag: "HomeScreen")], timeout: 10.0) // Second pass: without showIdMode for actual translations app.terminate() applangaUITest = ApplangaUITest(app: app, enableShowIdMode: false) app.launch() wait(for: [applangaUITest!.takeScreenshot(tag: "HomeScreen")], timeout: 10.0) } } ``` ```objc // Objective-C: Automated screenshot capture in UITests #import @interface MyUITestCase : XCTestCase @property ApplangaUITest *applangaUITest; @end @implementation MyUITestCase - (void)setUp { [super setUp]; self.continueAfterFailure = NO; XCUIApplication* app = [[XCUIApplication alloc] init]; self.applangaUITest = [[ApplangaUITest alloc] initWithApp:app enableShowIdMode:false]; [app launch]; } - (void)testCaptureScreenshots { XCUIApplication *app = [[XCUIApplication alloc] init]; // Home screen NSArray* expectations = [NSArray arrayWithObject:[self.applangaUITest takeScreenshotWithTag:@"HomeScreen"]]; [self waitForExpectations:expectations timeout:10]; // Navigate to next screen [app.buttons[@"Next"] tap]; expectations = [NSArray arrayWithObject:[self.applangaUITest takeScreenshotWithTag:@"NextScreen"]]; [self waitForExpectations:expectations timeout:10]; } @end ``` -------------------------------- ### Enable Show ID Mode for SwiftUI Screenshots Source: https://github.com/applanga/sdk-ios/blob/master/README.md This Swift code demonstrates how to enable the `showIdMode` for ApplangaUITest in SwiftUI projects. When enabled, it returns string IDs instead of translated strings, which is crucial for accurately linking string positions on screenshots during the localization process. ```swift let app = XCUIApplication() let applangaUITest = ApplangaUITest(app: app, enableShowIdMode: true) app.launch() ``` -------------------------------- ### Change App Language at Runtime (Swift & Objective-C) Source: https://context7.com/applanga/sdk-ios/llms.txt Dynamically switch the application's display language without requiring a restart. This involves updating translation groups and then setting the desired language. A UI recreation might be necessary to reflect the changes. ```swift // Swift: Change to a specific language func changeAppLanguage(to language: String) { // First update to ensure language is available Applanga.updateGroups(nil, andLanguages: [language]) { updateSuccess in if updateSuccess { let languageChangedSuccess = Applanga.setLanguage(language) if languageChangedSuccess { print("Language changed to \(language)") // Recreate UI to reflect new language let storyboard = UIStoryboard(name: "Main", bundle: nil) if let rootVC = storyboard.instantiateInitialViewController() { UIApplication.shared.windows.first?.rootViewController = rootVC UIApplication.shared.windows.first?.makeKeyAndVisible() } } else { print("Failed to set language to \(language)") } } } } // Usage changeAppLanguage(to: "es-MX") // Spanish (Mexico) changeAppLanguage(to: "de") // German // Reset to device language Applanga.setLanguage(nil) ``` ```objc // Objective-C: Change to a specific language + (void) changeAppLanguage:(NSString *)language { [Applanga updateGroups:nil andLanguages:@[language] withCompletionHandler:^(BOOL updateSuccess) { if (updateSuccess) { BOOL languageChangedSuccess = [Applanga setLanguage:language]; if (languageChangedSuccess) { NSLog(@"Language changed to %@", language); // Recreate UI to reflect new language } else { NSLog(@"Failed to set language to %@", language); } } }]; } // Reset to device language [Applanga setLanguage:nil]; ``` -------------------------------- ### Enable Placeholder Conversion in Plist Source: https://github.com/applanga/sdk-ios/blob/master/README.md Enable the automatic conversion of string placeholders between iOS (`%@`) and Android (`%s`) styles. This facilitates cross-platform compatibility for formatted strings. ```xml ApplangaConvertPlaceholders ``` -------------------------------- ### Direct Plural String Calls (JavaScript) Source: https://github.com/applanga/sdk-ios/blob/master/README.md Demonstrates direct calls to `Applanga.getPluralString` for pluralization in both UIWebView and WKWebView contexts. Supports passing arguments for dynamic string formatting. ```javascript //UIWebView translation = Applanga.getPluralString('APPLANGA_ID', 'one') //WKWebView Applanga.getPluralString('APPLANGA_ID', 'one', undefined, undefined, function(translation) { }) ``` ```javascript //UIWebView translation = Applanga.getPluralString('APPLANGA_ID', 'one', 'arg1;arg2;etc', ';') //WKWebView Applanga.getPluralString('APPLANGA_ID', 'one', 'arg1;arg2;etc', ';', function(translation) { }) ``` -------------------------------- ### Named Arguments in Strings (Swift and Objective-C) Source: https://context7.com/applanga/sdk-ios/llms.txt Allows replacement of placeholders within translated strings using dynamic values provided via a dictionary of named arguments. This feature supports both Swift and Objective-C and allows translators to reorder arguments in different languages. ```swift // Swift example with named arguments var args: [String: String] = ["userName": "John", "itemCount": "5", "storeName": "Apple Store"] let message = Applanga.localizedString(forKey: "purchase_confirmation", withDefaultValue: "Hello %{userName}, you purchased %{itemCount} items from %{storeName}", andArguments: args) // Output: "Hello John, you purchased 5 items from Apple Store" // On Applanga dashboard, the string would be: // "purchase_confirmation" = "Hello %{userName}, you purchased %{itemCount} items from %{storeName}" // Translators can reorder arguments: "Hola %{userName}, compraste %{itemCount} artículos en %{storeName}" ``` ```objective-c // Objective-C example with named arguments NSDictionary* args = @{@"userName": @"John", @"itemCount": @"5", @"storeName": @"Apple Store"}; NSString *message = [Applanga localizedStringForKey:@"purchase_confirmation" withDefaultValue:@"Hello %{userName}, you purchased %{itemCount} items from %{storeName}" andArguments:args]; ``` -------------------------------- ### WebView Translation with WKWebView (Swift) Source: https://context7.com/applanga/sdk-ios/llms.txt Translates HTML content within WKWebView instances using Applanga's JavaScript API. This requires loading HTML strings that include Applanga directives and potentially JavaScript functions for dynamic updates. Ensure the Applanga SDK is properly initialized. ```swift // Swift: WKWebView with Applanga import WebKit class WebViewController: UIViewController { var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() webView = WKWebView(frame: view.bounds) view.addSubview(webView) let html = """

Default Title

Hello %{user}, you have %{count} messages

""" webView.loadHTMLString(html, baseURL: nil) } } ``` -------------------------------- ### Pass Arguments for String Translation in HTML and JavaScript Source: https://github.com/applanga/sdk-ios/blob/master/README.md This demonstrates passing arguments to Applanga for string translation. Arguments can be provided as a comma-separated list via the `applanga-args` attribute in HTML or as a string in JavaScript. The SDK formats the translated string using these arguments. ```html
***This will be replaced with the value of APPLANGA_ID*** ***and formatted with arguments***
``` ```javascript //UIWebView translation = Applanga.getString('APPLANGA_ID', 'arg1,arg2,etc') //WKWebView Applanga.getString('APPLANGA_ID', 'arg1,arg2,etc', undefined, undefined, undefined, undefined, function(translation) { }) ``` -------------------------------- ### Update Applanga Settings File Automatically (Python) Source: https://context7.com/applanga/sdk-ios/llms.txt A Python script included in the SDK that automatically checks for and downloads newer versions of the Applanga settings file. It recursively searches for *.applanga files, communicates with the Applanga API, and updates the local file if a newer version is available. This script is designed to be run from the command line. ```python # Python script: settingsfile_update.py (included in SDK) #!/usr/bin/env python import os import tarfile import json import sys from urllib.request import urlopen, urlretrieve # Usage: python settingsfile_update.py /path/to/project # Searches for *.applanga files recursively # Checks Applanga API for newer version # Downloads and replaces if update available # Logs: "Settingsfile updated!" or "Settingsfile up-to-date" ``` -------------------------------- ### Pluralization by Quantity in Objective-C and Swift Source: https://github.com/applanga/sdk-ios/blob/master/README.md Retrieve localized strings by specifying a quantity, allowing Applanga to automatically select the appropriate pluralization rule. Also shows how to format the string with the quantity. ```objc //objc // get a string in the given quantity [Applanga localizedStringForKey:@"APPLANGA_ID" withDefaultValue:@"default value" andArguments:nil andPluralRule:ALPluralRuleForQuantity(quantity)] // or get a formatted string with the given quantity [NSString localizedStringWithFormat:[Applanga localizedStringForKey:@"APPLANGA_ID" withDefaultValue:@"default value" andArguments:nil andPluralRule:ALPluralRuleForQuantity(quantity)], quantity] ``` ```swift //swift // get a string in the given quantity Applanga.localizedString(forKey: "APPLANGA_ID", withDefaultValue: "default value", andArguments: nil, andPluralRule: ALPluralRuleForQuantity(quantity)) //or get a formatted string with the given quantity NSString.localizedStringWithFormat(NSString(string:(Applanga.localizedString(forKey: "APPLANGA_ID", withDefaultValue: "default", andArguments: nil, andPluralRule: ALPluralRuleForQuantity(quantity))))), quantity) ``` -------------------------------- ### Pluralization Rules in Objective-C and Swift Source: https://github.com/applanga/sdk-ios/blob/master/README.md Handle pluralization for strings based on predefined rules (zero, one, two, few, many, other) or a specified quantity. This ensures correct grammatical forms for varying numbers. ```objc //objc // get translated string in given pluralisation rule (one) [Applanga localizedStringForKey:@"APPLANGA_ID" withDefaultValue:@"default value" andArguments:nil andPluralRule:ALPluralRuleOne] ``` ```swift //swift Applanga.localizedString(forKey: "no default", withDefaultValue: "default", andArguments: nil, andPluralRule: ALPluralRule.one) ``` -------------------------------- ### Localize Strings with Named Arguments in Objective-C and Swift Source: https://github.com/applanga/sdk-ios/blob/master/README.md Translate strings that contain placeholders for dynamic arguments. A dictionary of string key-value pairs is passed to replace placeholders like %{someArg}. This allows for flexible and dynamic text construction. ```objc //objc // if you pass a string:string dictionary you can get translated string // with named arguments. %{someArg} %{anotherArg} etc. NSDictionary* args = @{@"someArg": @"awesome",@"anotherArg": @"crazy"}; [Applanga localizedStringForKey:@"APPLANGA_ID" withDefaultValue:@"default value" andArguments:args] ``` ```swift //swift var args: [String: String] = ["someArg": "awesome", "anotherArg": "crazy"]; Applanga.localizedString(forKey: "APPLANGA_ID", withDefaultValue: "default", andArguments: args) ``` -------------------------------- ### Configure Custom Language Fallback in Info.plist Source: https://github.com/applanga/sdk-ios/blob/master/README.md This dictionary-based configuration allows defining a custom fallback order for specific languages, overriding system or default fallbacks. Each specified language array dictates the fallback sequence for its corresponding key language. The language itself must be included in its fallback array. ```xml ... ApplangaCustomLanguageFallback es-MX es-MX es-US es en-US en-GB de-DE ... ``` -------------------------------- ### SwiftUI Text Localization Extension Source: https://github.com/applanga/sdk-ios/blob/master/README.md This Swift extension for the Text view in SwiftUI allows for easy localization of text components using Applanga keys. It provides initializers to directly use Applanga keys for displaying localized strings, with an option to specify a default value if the key is not found. ```swift extension Text { init(applangaKey : String){ self.init(NSLocalizedString(applangaKey, tableName: nil, bundle: Bundle.main, value: "", comment:"")) } init(applangaKey : String, defaultValue : String){ self.init(NSLocalizedString(applangaKey, tableName: nil, bundle: Bundle.main, value: defaultValue, comment:"")) } } ``` -------------------------------- ### Take Screenshot in UITests (Objective-C) Source: https://github.com/applanga/sdk-ios/blob/master/README.md Captures and uploads a screenshot within an Xcode UITest using `ApplangaUITest`. Requires specifying a tag/screen name and waiting for the operation to complete. ```objc //objc NSArray* expectations = [NSArray arrayWithObject:[self.applangaUITest takeScreenshotWithTag:@"ScreenName"]]; [self waitForExpectations:expectations timeout:10]; ``` -------------------------------- ### Basic String Localization in Swift Source: https://context7.com/applanga/sdk-ios/llms.txt Retrieves translated strings for the current device locale in Swift projects. It supports custom default values and integrates with standard iOS localization methods. The Applanga SDK automatically intercepts `NSLocalizedString` calls. ```swift import Applanga // Get translated string with default value let welcomeMessage = Applanga.localizedString(forKey: "welcome_message", withDefaultValue: "Welcome to our app") // Use in UI elements let label = UILabel() label.text = Applanga.localizedString(forKey: "hello_world", withDefaultValue: "Hello World") // Standard iOS method also works (automatically intercepted by Applanga) let text = NSLocalizedString("app_title", value: "My App", comment: "") ``` -------------------------------- ### Show Applanga Screenshot Menu on TV OS Source: https://github.com/applanga/sdk-ios/blob/master/README.md This Swift code snippet demonstrates how to make the Applanga screenshot menu visible on tvOS after the Draft Mode has been enabled. This allows for capturing screenshots with translations directly on the TV device. ```swift Applanga.setScreenShotMenuVisible(true) ``` -------------------------------- ### Automatic Applanga Settings File Update Script (Manual Integration) Source: https://github.com/applanga/sdk-ios/blob/master/README.md Use this script in Xcode's Build Phases for manual SDK integration to update the Applanga Settings File. It provides the latest translations, with fallbacks to cached data or the settings file. ```bash bash "$BUILT_PRODUCTS_DIR/$FRAMEWORKS_FOLDER_PATH/Applanga.xcframework/update-settingsfile.sh" "$SOURCE_ROOT/$TARGET_NAME" ``` -------------------------------- ### Branching Support in Draft Mode (Swift) Source: https://context7.com/applanga/sdk-ios/llms.txt Enables managing different translation branches for feature development and testing within the Applanga SDK. When Draft Mode is enabled, users can switch branches via a gesture, and the app will restart to apply the selected branch. This requires SDK version 2.0.218+ and an updated settings file. ```swift // Swift: Branching in Draft Mode // When Draft Mode is enabled: // 1. App uses branch defined in settings file by default // 2. Open Draft Mode menu (two-finger swipe down) // 3. Switch to different branch in Draft Mode UI // 4. Restart app to apply new branch // 5. All screenshots are tagged with current branch // Check logs for: // "Branching is enabled." // Note: Requires SDK version 2.0.218+ and updated Settings File ``` -------------------------------- ### Update Specific Groups and Languages in Objective-C and Swift Source: https://github.com/applanga/sdk-ios/blob/master/README.md Request an update for a specific set of content groups and languages. This is useful for managing updates more granularly and reducing bandwidth usage. A completion handler is invoked upon completion. ```objc //objc NSArray* groups = @[@"GroupA", @"GroupB"]; NSArray* languages = @[@"en", @"de", @"fr"]; [Applanga updateGroups:groups andLanguages:languages withCompletionHandler:^(BOOL success) { //called if update is complete }]; ``` ```swift //swift var groups: [String] = ["GroupA", "GroupB"] var languages: [String] = ["en", "de", "fr"] Applanga.updateGroups(groups, andLanguages: languages, withCompletionHandler: {(success: Bool) in //called if update is complete }) ``` -------------------------------- ### Direct Quantity String Calls (JavaScript) Source: https://github.com/applanga/sdk-ios/blob/master/README.md Shows how to use `Applanga.getQuantityString` for pluralization based on quantity. This function can be used in UIWebView and WKWebView, with options for arguments and callbacks. ```javascript //UIWebView translation = Applanga.getQuantityString('APPLANGA_ID', 42) //WKWebView Applanga.getQuantityString('APPLANGA_ID', 42, undefined, undefined, function(translation) { }) ``` ```javascript //UIWebView translation = Applanga.getQuantityString('APPLANGA_ID', 42, 'arg1;arg2;etc', ';') //WKWebView Applanga.getQuantityString('APPLANGA_ID', 42, 'arg1;arg2;etc', ';', function(translation) { }) ``` -------------------------------- ### Set App Language in Swift and Objective-C Source: https://github.com/applanga/sdk-ios/blob/master/README.md This snippet demonstrates how to set the current language in the Applanga SDK. It accepts an ISO language string and returns a boolean indicating success. To reset to the device's default language, pass `nil`. UI reinitialization is required after changing the language. ```swift var success: Bool = Applanga.setLanguage(language) Applanga.setLanguage(nil); ``` ```objc Applanga.setLanguage(nil); ``` -------------------------------- ### Basic String Localization in Objective-C Source: https://context7.com/applanga/sdk-ios/llms.txt Retrieves translated strings for the current device locale in Objective-C projects. It supports custom default values and integrates with standard iOS localization methods. The Applanga SDK automatically intercepts `NSLocalizedStringWithDefaultValue` calls. ```objective-c #import // Get translated string with default value NSString *welcomeMessage = [Applanga localizedStringForKey:@"welcome_message" withDefaultValue:@"Welcome to our app"]; // Use in UI elements UILabel *label = [[UILabel alloc] init]; label.text = [Applanga localizedStringForKey:@"hello_world" withDefaultValue:@"Hello World"]; // Standard iOS method also works (automatically intercepted by Applanga) NSString *text = NSLocalizedStringWithDefaultValue(@"app_title", nil, NSBundle.mainBundle, @"My App", @""); ``` -------------------------------- ### Enable System Language Fallback in Info.plist Source: https://github.com/applanga/sdk-ios/blob/master/README.md This setting configures the Applanga SDK to use the device's system language priority for localization and string fallback. If a string is not found for a given language, the SDK will attempt to use the next language in the system's priority list. ```xml ... ApplangaLanguageFallback system ... ``` -------------------------------- ### Change App Language at Runtime in Objective-C Source: https://github.com/applanga/sdk-ios/blob/master/README.md Dynamically change the application's language during runtime. This method takes a language code as input and returns a boolean indicating success. This allows for on-the-fly language switching. ```objc //objc BOOL success = [Applanga setLanguage: language]; ``` -------------------------------- ### Initialize Applanga for UIWebView in JavaScript Source: https://github.com/applanga/sdk-ios/blob/master/README.md This JavaScript snippet is used to initialize Applanga for content translation within a `UIWebView`. It checks for the availability of `ApplangaNative` and recursively calls itself with a delay if not found, ensuring Applanga is ready to load scripts. ```javascript window.initApplanga = function() { if(typeof window.ApplangaNative !== 'undefined') { window.ApplangaNative.loadScript(); } else { setTimeout(window.initApplanga, 180); } }; window.initApplanga(); ``` -------------------------------- ### Use JSON for Named Arguments in HTML and JavaScript Source: https://github.com/applanga/sdk-ios/blob/master/README.md This demonstrates using JSON objects for named arguments in Applanga translations. By setting `applanga-args-separator` to "json", you can pass a JSON string containing key-value pairs, which are then used to format the translated string. ```html
***This will be replaced with the value of APPLANGA_ID*** ***and formatted with json arguments***
``` ```javascript //UIWebView translation = Applanga.getString('APPLANGA_ID', "{'arg1':'value1', 'arg2':'value2', 'arg3':'etc'}", 'json') //WKWebView Applanga.getString('APPLANGA_ID', "{'arg1':'value1', 'arg2':'value2', 'arg3':'etc'}", 'json', undefined, undefined, undefined, function(translation) { }) ``` -------------------------------- ### Enable Show ID Mode (JavaScript) Source: https://github.com/applanga/sdk-ios/blob/master/README.md Activates or deactivates the 'Show ID Mode' in the Applanga SDK. When enabled, string IDs are returned instead of translations, useful for screenshot collection accuracy. This should not be used in production. ```javascript Applanga.setShowIdModeEnabled(true); ``` -------------------------------- ### Automatic Applanga Settings File Update Script (Swift Package Manager) Source: https://github.com/applanga/sdk-ios/blob/master/README.md Add this script to Xcode's Build Phases for automatic Applanga Settings File updates when using Swift Package Manager. It ensures the app has the latest translations, using cached versions or the settings file as fallback. ```bash bash "${BUILD_DIR%Build/*}/SourcePackages/checkouts/sdk-ios/Applanga.xcframework/update-settingsfile.sh" "$SOURCE_ROOT/$TARGET_NAME" ``` -------------------------------- ### Specify Default Languages in Plist Source: https://github.com/applanga/sdk-ios/blob/master/README.md Define a comma-separated list of default languages to be automatically fetched during updates. These are added to any languages specified in update calls. ```xml ApplangaUpdateLanguages en,de-at,fr ``` -------------------------------- ### Update Content and Change App Language in Objective-C Source: https://github.com/applanga/sdk-ios/blob/master/README.md This Objective-C code snippet shows how to update Applanga content and then change the app's language. It uses a completion handler to check if the content update was successful before attempting to set the new language. If the language change is successful, UI re-creation is recommended. ```objc + (void) changeAppLanguage:(NSString *)language { [Applanga updateGroups:nil andLanguages:@[language] withCompletionHandler:^( BOOL updateSuccess ){ if(updateSuccess){ BOOL languageChangedSuccess = [Applanga setLanguage:language]; if(languageChangedSuccess) { //recreate ui } } }]; } ``` -------------------------------- ### Localize Strings in Objective-C and Swift Source: https://github.com/applanga/sdk-ios/blob/master/README.md Retrieve localized strings for the current device locale. Supports custom default values if the localized string is not found. This is the fundamental method for accessing translated text. ```objc //objc // get translated string for the current device locale [Applanga localizedStringForKey:@"APPLANGA_ID" withDefaultValue:@"default value"]; ``` ```swift //swift Applanga.localizedString(forKey: "APPLANGA_ID", withDefaultValue: "default value") ```