• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

crowdin/mobile-sdk-ios: Crowdin iOS SDK delivers all new translations from Crowd ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

crowdin/mobile-sdk-ios

开源软件地址(OpenSource Url):

https://github.com/crowdin/mobile-sdk-ios

开源编程语言(OpenSource Language):

Swift 98.3%

开源软件介绍(OpenSource Introduction):

Crowdin iOS SDK

Crowdin iOS SDK delivers all new translations from Crowdin project to the application immediately. So there is no need to update this application via App Store to get the new version with the localization.

The SDK provides:

  • Over-The-Air Content Delivery – the localized content can be sent to the application from the project whenever needed.
  • Real-Time Preview – all the translations that are done in the Editor can be shown in your version of the application in real-time. View the translations already made and the ones you're currently typing in.
  • Screenshots – all the screenshots made in the application may be automatically sent to your Crowdin project with tagged source strings.

Cocoapods Cocoapods platforms Swift Package Manager GitHub Release Date GitHub contributors GitHub License

Azure DevOps builds (branch) Azure DevOps tests (branch) codecov

Table of Contents

Requirements

  • Xcode 10.2
  • Swift 4.2
  • iOS 9.0

Dependencies

  • Starscream - Websockets in swift for iOS and OSX.

Installation

Cocoapods

  1. Cocoapods

    To install Crowdin iOS SDK via cocoapods, make sure you have cocoapods installed locally. If not, install it with following command: sudo gem install cocoapods.

    Detailed instruction can be found here.

    Add the following line to your Podfile:

    pod 'CrowdinSDK'
  2. Cocoapods spec repository

    target 'MyApp' do
      pod 'CrowdinSDK'
    end
  3. Working with App Extensions

    Upon pod install result, you might experience some building issues in case your application embeds target extensions.

    Example error:

    'shared' (Swift) / 'sharedApplication' (Objective-C) is unavailable: not available on iOS (App Extension) - Use view controller based solutions where appropriate instead.

    In this scenario you'll need to add a post_install script to your Podfile

    post_install do |installer|
    
      extension_api_exclude_pods = ['CrowdinSDK']
    
      installer.pods_project.targets.each do |target|
    
          # the Pods contained into the `extension_api_exclude_pods` array
          # have to get the value (APPLICATION_EXTENSION_API_ONLY) set to NO
          # in order to work with service extensions
    
          if extension_api_exclude_pods.include? target.name
            target.build_configurations.each do |config|
              config.build_settings['APPLICATION_EXTENSION_API_ONLY'] = 'NO'
            end
          end
        end
    end

    Then run pod install again to fix it.

After you've added CrowdinSDK to your Podfile, run pod install in your project directory, open App.xcworkspace and build it.

Swift Package Manager

Once you have your Swift package set up, adding CrowdinSDK as a dependency is as easy as adding it to the dependencies value of your Package.swift.

‼️Swift Package Manager support added in version 1.4.0‼️

dependencies: [
    .package(url: "https://github.com/crowdin/mobile-sdk-ios.git", from:"1.4.0")
]

Setup

To configure iOS SDK integration you need to:

  • Upload your strings/stringsdict localization files to Crowdin. If you have ready translations, you can also upload them.
  • Set up Distribution in Crowdin.
  • Set up SDK and enable Over-The-Air Content Delivery feature.

Distribution is a CDN vault that mirrors the translated content of your project and is required for integration with iOS app.

To manage distributions open the needed project and go to Over-The-Air Content Delivery. You can create as many distributions as you need and choose different files for each. You’ll need to click the Release button next to the necessary distribution every time you want to send new translations to the app.

  1. Enable Over-The-Air Content Delivery in your Crowdin project so that application can pull translations from CDN vault.

  2. In order to start using CrowdinSDK you need to initialize it in AppDelegate or in Info.plist


Notes:

  • The translation downloading happens asynchronously after launching the app. The downloaded translations will be used after the next launch of the app otherwise the previously cached translations will be used (or local translations if a cache does not exist).
  • The CDN feature does not update the localization files. if you want to add new translations to the localization files you need to do it yourself.
  • Once SDK receives the translations, it's stored on the device as application files for further sessions to minimize requests the next time the app starts. Storage time can be configured using intervalUpdatesEnabled option.
  • CDN caches all the translation in release for up to 15 minutes and even when new translations are released in Crowdin, CDN may return it with a delay.

Setup with AppDelegate

Open AppDelegate.swift file and add:

import CrowdinSDK

In application method add:

let crowdinProviderConfig = CrowdinProviderConfig(hashString: "{your_distribution_hash}",
  sourceLanguage: "{source_language}")

CrowdinSDK.startWithConfig(crowdinSDKConfig, completion: {
    // SDK is ready to use, put code to change language, etc. here
})
Config option Description Example
hashString Distribution Hash hashString: "7a0c1ee2622bc85a4030297uo3b"
sourceLanguage Source language code in your Crowdin project. ISO 639-1 sourceLanguage: "en"
Objective-C

In AppDelegate.m add:

@import CrowdinSDK

or

#import<CrowdinSDK/CrowdinSDK.h>

In application method add:

CrowdinProviderConfig *crowdinProviderConfig = [[CrowdinProviderConfig alloc] initWithHashString:@"" sourceLanguage:@""];
CrowdinSDKConfig *config = [[[CrowdinSDKConfig config] withCrowdinProviderConfig:crowdinProviderConfig]];

[CrowdinSDK startWithConfig:config completion:^{
    // SDK is ready to use, put code to change language, etc. here
}];

If you have pure Objective-C project, then you will need to do some additional steps:

Add the following code to your Library Search Paths:

$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)

Add use_frameworks! to your Podfile.

Setup with Info.plist

Open Info.plist file and add:

CrowdinDistributionHash - Crowdin CDN hash value for current project (String value).

CrowdinSourceLanguage - Source language code (ISO 639-1) for current project on crowdin server (String value).

In AppDelegate you should call start method: CrowdinSDK.start() for Swift, and [CrowdinSDK start] for Objective-C.

Note! Using this setup method you will unable to set up additional Screenshots and Real-Time Preview project features.

SwiftUI support

SwiftUI doesn’t have automatic support for now. It will work only when you pass localised string using NSLocalizedString(“key”, comment: “comment”). It means that you will need to update all localised strings in SwiftUI application. For more comfortable usage you can use out String extension for localisation: “key”.cw_localized.

Example:

Text(NSLocalizedString(“key”, comment: “comment”))

or

Text(“key”.cw_localized)

After we add SwiftUI support you will need just simply remove call of cw_localized method.

Advanced Features

Real-Time Preview

All the translations that are done in the Editor can be shown in the application in real-time. View the translations already made and the ones you're currently typing in.

Add the code below to your Podfile:

use_frameworks!
target 'your-app' do
    pod 'CrowdinSDK'
    pod 'CrowdinSDK/LoginFeature' // Required for Real-Time Preview
    pod 'CrowdinSDK/RealtimeUpdate' // Required for Real-Time Preview
    pod 'CrowdinSDK/Settings' // Optional. To add 'settings' floating button
end

Open AppDelegate.swift file and in application method add:

let crowdinProviderConfig = CrowdinProviderConfig(hashString: "{your_distribution_hash}",
    sourceLanguage: "{source_language}")

var loginConfig: CrowdinLoginConfig
do {
    loginConfig = try CrowdinLoginConfig(clientId: "{client_id}",
       clientSecret: "{client_secret}",
       scope: "project",
       redirectURI: "{redirectURI}",
       organizationName: "{organization_name}")
} catch {
    print(error)
    // CrowdinLoginConfig initialization error handling, typically for empty values and for wrong redirect URI value.
}

let crowdinSDKConfig = CrowdinSDKConfig.config().with(crowdinProviderConfig: crowdinProviderConfig)
    .with(loginConfig: loginConfig)
    .with(settingsEnabled: true)
    .with(realtimeUpdatesEnabled: true)

CrowdinSDK.startWithConfig(crowdinSDKConfig, completion: {
    // SDK is ready to use, put code to change language, etc. here
})
Objective-C
CrowdinProviderConfig *crowdinProviderConfig = [[CrowdinProviderConfig alloc] initWithHashString:@"" sourceLanguage:@""];

NSError *error;
CrowdinLoginConfig *loginConfig = [[CrowdinLoginConfig alloc] initWithClientId:@"{client_id}" clientSecret:@"{client_secter}" scope:@"project" organizationName:@"{organization_name}" error:&error];

if (!error) {
    CrowdinSDKConfig *config = [[[CrowdinSDKConfig config] withCrowdinProviderConfig:crowdinProviderConfig] withLoginConfig:loginConfig];

    [CrowdinSDK startWithConfig:config completion:^{
       // SDK is ready to use, put code to change language, etc. here
    }];
} else {
    NSLog(@"%@", error.localizedDescription);
    // CrowdinLoginConfig initialization error handling, typically for empty values and for wrong redirect URI value.
}
Config option Description Example
hashString Distribution Hash hashString: "7a0c1ee2622bc85a4030297uo3b"
sourceLanguage Source language code in your Crowdin project. ISO 639-1 sourceLanguage: "en"
clientId, clientSecret Crowdin OAuth Client ID and Client Secret clientId: "gpY2yTbCVGEelrcx3TYB", clientSecret: "Xz95t0ASVgbvKaZbFB4SMHQzdUl1MSgSTabEDx9T"
scope Define the access scope for personal tokens scope: "project"
redirectURI A custom URL for your app. Read more in the article. It's an optional value. You should set it in case you want to use a specific URL scheme. In case you set a scheme which is not supported by your application init method will throw an exception. redirectURI: "crowdintest://"
organizationName An Organization domain name.
ℹ️ for Crowdin Enterprise users only
organizationName: "mycompany"
settingsEnabled Enable floating widget to easily access the features of SDK settingsEnabled: true
realtimeUpdatesEnabled Enable Real-Time Preview feature realtimeUpdatesEnabled: true

The last step is to handle authorization callback in your application:

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
    CrowdinSDK.handle(url: url)
}
Objective-C
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    return [CrowdinSDK handleWithUrl:url];
}

If you are using SceneDelegate, you need to handle callback in the SceneDelegate class implement method:

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    guard let url = URLContexts.first?.url else { return }
    CrowdinSDK.handle(url: url)
}
Objective-C
- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts {
    return [CrowdinSDK handleWithUrl:url];
}

Screenshots

Enable if you want all the screenshots made in the application to be automatically sent to your Crowdin project with tagged strings. This will provide additional context for translators.

Add the code below to your Podfile:

use_frameworks!
target 'your-app' do
    pod 'CrowdinSDK'
    pod 'CrowdinSDK/LoginFeature' // Required for Screenshots
    pod 'CrowdinSDK/Screenshots' // Required for Screenshots
    pod 'CrowdinSDK/Settings' // Optional. To add 'settings' button
end

Open AppDelegate.swift file and in application method add:

let crowdinProviderConfig = CrowdinProviderConfig(hashString: "{your_distribution_hash}",
    sourceLanguage: "{source_language}")

var loginConfig: CrowdinLoginConfig
do {
   loginConfig = try CrowdinLoginConfig(clientId: "{client_id}",
       clientSecret: "{client_secret}",
       scope: "project.screenshot",
       redirectURI: "{redirectURI}",
       organizationName: "{organization_name}")
} catch {
    print(error)
    // CrowdinLoginConfig initialization error handling, typically for empty values and for wrong redirect URI value.
}

let crowdinSDKConfig = CrowdinSDKConfig.config().with(crowdinProviderConfig: crowdinProviderConfig)
    .with(screenshotsEnabled: true)
    .with(loginConfig: loginConfig)
    .with(settingsEnabled: true)

CrowdinSDK.startWithConfig(crowdinSDKConfig, completion: {
    // SDK is ready to use, put code to change language, etc. here
})
Objective-C
CrowdinProviderConfig *crowdinProviderConfig = [[CrowdinProviderConfig alloc] initWithHashString:@"" sourceLanguage:@""];

NSError *error;
CrowdinLoginConfig *loginConfig = [[CrowdinLoginConfig alloc] initWithClientId:@"{client_id}" clientSecret:@"{client_secter}" scope:@"project.screenshot" organizationName:@"{organization_name}" error:&error];

if (!error) {
    CrowdinSDKConfig *config = [[[CrowdinSDKConfig config] withCrowdinProviderConfig:crowdinProviderConfig] withLoginConfig:loginConfig];

    [CrowdinSDK startWithConfig:config completion:^{
        // SDK is ready to use, put code to change language, etc. here
    }];
} else {
    NSLog(@"%@", error.localizedDescription);
    // CrowdinLoginConfig initialization error handling, typically for empty values and for wrong redirect URI value.
}
Config option Description Example
hashString Distribution Hash hashString: "7a0c1ee2622bc85a4030297uo3b"
sourceLanguage Source language code in your Crowdin project. ISO 639-1 sourceLanguage: "en"
clientId, clientSecret Crowdin OAuth Client ID and Client Secret clientId: "gpY2yTbCVGEelrcx3TYB", clientSecret: "Xz95t0ASVgbvKaZbFB4SMHQzdUl1MSgSTabEDx9T"
scope Define the access scope for personal tokens scope: "project.screenshot"
redirectURI A custom URL for your app. Read more in the article. It's an optional value. You should set it in case you want to use a specific URL scheme. In case you set a scheme which is not supported by your application init method will throw an exception. redirectURI: "crowdintest://"
organizationName An Organization domain name.
ℹ️ for Crowdin Enterprise users only
organizationName: "mycompany"
settingsEnabled Enable floating widget to easily access the features of SDK settingsEnabled: true
screenshotsEnabled Enable Screenshots feature screenshotsEnabled: true

The last step is to handle authorization callback in your application:

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
    CrowdinSDK.handle(url: url)
}
Objective-C
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    return [CrowdinSDK handleWithUrl:url];
}

If you are using SceneDelegate, you need to handle callback in the SceneDelegate class implement method:

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    guard let url = URLContexts.first?.url else { return }
    CrowdinSDK.handle(url: url)
}
Objective-C
- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts {
    return [CrowdinSDK handleWithUrl:url];
}

You could also define (optional) your own handler to take a screenshot (for example, clicking on some button in your application):

let feature = ScreenshotFeature.shared {
    feature.captureScreenshot(name: String(Date().timeIntervalSince1970), success: {
        CrowdinLogsCollector.shared.add(log: CrowdinLog(type: .info, message: message))
        self?.showToast(message)
    }, errorHandler: { (error) in
        let message = "Error while capturing screenshot - \(error?.localizedDescription ?? "Unknown")"
        CrowdinLogsCollector.shared.add(log: CrowdinLog(type: .error, message: message))
        self?.showToast(message)
    })
}

or even capture screenshots of a separate UIView.

Notes

  1. Configuring translation update interval

    By default SDK is looking for new translation once per application load every 15 minutes. You can update translations in application every defined time interval. To enable this feature add pod CrowdinSDK/IntervalUpdate to your pod file:

    pod 'CrowdinSDK/IntervalUpdate'

    Then enable this option in CrowdinSDKConfig:

    .with(intervalUpdatesEnabled: true, interval: {interval})

    interval - defines translations update time interval in seconds. Minimum allowed interval is 15 minutes.

  2. R-Swift applications are also supported by Crowdin iOS SDK.

  3. To change SDK target language on the fly regardless of device locale use the following method:

    CrowdinSDK.enableSDKLocalization(true, localization: “<language_code>”)

    <language_code> - target language code in ISO 639-1 format.

  4. Currently, Language Mapping is not supported by iOS SDK.

  5. Crowdin iOS SDK provides detailed debug mode - "Logs" tab in the Settings floating button module and logging into XCode console. To enable console logging, add the following option to your CrowdinSDKConfig

    .with(debugEnabled: true)
  6. Log callback. Crowdin SDK collects log messages for all actions that made by SDK (login/logout, download languages, API calls). This callback returns Log text each time a new Log is created. To subscribe on receiving Log messages just add a new callback like this:

    CrowdinSDK.setOnLogCallback { logMessage in
       print("LOG MESSAGE - \(logMessage)")
    }

File Export Patterns

You can set file export patterns and check existing ones using File


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap