Выбор поставщика AI-сервисов
Зарегистрируйте SDK поставщиков, включённые в приложение, затем выберите поставщика, которого AIBudsAISDK будет использовать для последующих AI-операций.
Предварительные условия
- Базовый AIBuds SDK инициализирован.
- Приложение установило и скомпоновало хотя бы один SDK поставщика.
- Выбранный поставщик входит в массив, переданный в
AIBudsAISDK.initialize(_:). - Данные устройства настроены до авторизации поставщика и AI-операций, зависящих от устройства.
Реализация с помощью AI
Реализуйте этот сценарий с AI
Используйте официальный навык «Выбор поставщика ИИ для AIBuds» и адаптируйте сценарий к приложению.
Прочитайте и выполните инструкции https://docs-aibuds.github.io/ru/skills/select-aibuds-ai-provider. Используйте этот навык, чтобы реализовать «Выбор поставщика ИИ для AIBuds» в данном iOS-проекте и проверить результат.API Reference
Framework
AIBudsAI.xcframework
Реализации поставщиков распространяются отдельно, в том числе AIBudsStarBurst.xcframework и AIBudsMagicHelper.xcframework.
Import
- Swift
- Objective-C
import AIBudsAI
import AIBudsAIFoundation
import AIBudsStarBurst
import AIBudsMagicHelper#import <AIBudsAI/AIBudsAI-Swift.h>
#import <AIBudsMagicHelper/AIBudsMagicHelper-Swift.h>
#import <AIBudsStarBurst/AIBudsStarBurst-Swift.h>Declaration
Жизненным циклом поставщиков управляет AIBudsAISDK. Их реализации соответствуют AIConnectSDK.
- Swift
- Objective-C
/// Initializes the SDK with the specified provider implementations.
/// - Parameter aiSDKs: The providers to register. Their order determines
/// recognition priority; a later provider using an already-registered
/// Bluetooth data protocol type is ignored.
/// - Returns: `true` when initialization succeeds; otherwise `false`.
public static func initialize( _ aiSDKs: [AIConnectSDK] ) -> Bool
/// The current AI service vendor.
static var aiServiceVendor: AIServiceVendor { get }
/// Sets the AI service vendor for the SDK.
/// - Parameter aiServiceVendor: The vendor used by subsequent AI services.
/// - Important: Call this method before using AI service-dependent functionality.
public static func setAIServiceVendor(_ aiServiceVendor: AIServiceVendor) -> Void
/// Returns all languages supported by the specified vendor.
/// - Parameter vendor: The vendor whose languages are requested.
/// - Returns: Supported languages, or an empty array when the vendor is `.none`
/// or its provider SDK is not registered.
public static func allSupportedLanguages(for vendor: AIServiceVendor) -> [AIServiceLanguage]
/// Returns the authentication initiation mode for the specified vendor.
/// - Parameter vendor: The vendor whose authentication mode is requested.
/// - Returns: The provider authentication mode.
public static func authenticationMode(for vendor: AIServiceVendor) -> AIAuthenticationMode
/// Indicates whether the device is authenticated for the specified vendor.
/// - Parameter vendor: The vendor whose authentication state is requested.
/// - Returns: `true` when the provider reports an authenticated device.
public static func isAuthenticated(for vendor: AIServiceVendor) -> Bool/// Initializes the SDK with the specified provider implementations.
/// - Parameter aiSDKs: The providers to register. Their order determines
/// recognition priority; a later provider using an already-registered
/// Bluetooth data protocol type is ignored.
/// - Returns: `YES` when initialization succeeds; otherwise `NO`.
+ (BOOL)initWithAISDKs:(NSArray<id <AIBudsAIConnectSDK>> * _Nonnull)aiSDKs;
/// The current AI service vendor.
@property(nonatomic, class, readonly) AIBudsAIServiceVendor aiServiceVendor;
/// Sets the AI service vendor for the SDK.
/// - Parameter aiServiceVendor: The vendor used by subsequent AI services.
/// - Important: Call this method before using AI service-dependent functionality.
+ (void)setAIServiceVendor:(enum AIBudsAIServiceVendor)aiServiceVendor;
/// Returns all languages supported by the specified vendor.
/// - Parameter vendor: The vendor whose languages are requested.
/// - Returns: Supported languages, or an empty array when the vendor is
/// `AIBudsAIServiceVendorNone` or its provider SDK is not registered.
+ (NSArray<AIBudsAIServiceLanguage *> * _Nonnull)allSupportedLanguagesForVendor:(enum AIBudsAIServiceVendor)vendor;
/// Returns the authentication initiation mode for the specified vendor.
/// - Parameter vendor: The vendor whose authentication mode is requested.
/// - Returns: The provider authentication mode.
+ (enum AIBudsAIAuthenticationMode)authenticationModeForVendor:(enum AIBudsAIServiceVendor)vendor;
/// Indicates whether the device is authenticated for the specified vendor.
/// - Parameter vendor: The vendor whose authentication state is requested.
/// - Returns: `YES` when the provider reports an authenticated device.
+ (BOOL)isAuthenticatedForVendor:(enum AIBudsAIServiceVendor)vendor;Поставщики AI-сервисов
| Swift | Objective-C | Описание |
|---|---|---|
.none | AIBudsAIServiceVendorNone | Поставщик не выбран. Это состояние по умолчанию. |
.starBurst | AIBudsAIServiceVendorStarBurst | StarBurst AI от ByteDance. |
.mltcloud | AIBudsAIServiceVendorMltcloud | MltCloud AI от Meilc. |
Актуальное перечисление приведено в AIServiceVendor.
Примеры использования
Регистрация SDK поставщиков
Обычно поставщики регистрируются один раз при запуске приложения.
- Swift
- Objective-C
import AIBudsAI
import AIBudsStarBurst
import AIBudsMagicHelper
let initialized = AIBudsAISDK.initialize([
StarBurstSDK.shared,
MagicHelperSDK.shared,
])
guard initialized else {
print("AIBudsAISDK initialization failed")
return
}#import <AIBudsAI/AIBudsAI-Swift.h>
#import <AIBudsMagicHelper/AIBudsMagicHelper-Swift.h>
#import <AIBudsStarBurst/AIBudsStarBurst-Swift.h>
BOOL initialized = [AIBudsAISDK initWithAISDKs:@[
[AIBudsStarBurstSDK shared],
[AIBudsMagicHelperSDK shared],
]];
if (!initialized) {
NSLog(@"AIBudsAISDK initialization failed");
return;
}Если приложение использует AIBudsAllInOneSDK, его инициализация может установить встроенных поставщиков. Не инициализируйте AIBudsAISDK повторно.
Выбор поставщика
- Swift
- Objective-C
let vendor: AIServiceVendor = .starBurst
AIBudsAISDK.setAIServiceVendor(vendor)
print("Selected provider: \(AIBudsAISDK.aiServiceVendor)")
print("Supported languages: \(AIBudsAISDK.allSupportedLanguages(for: vendor))")AIBudsAIServiceVendor vendor = AIBudsAIServiceVendorStarBurst;
[AIBudsAISDK setAIServiceVendor:vendor];
NSLog(@"Selected provider: %ld", (long)AIBudsAISDK.aiServiceVendor);
NSLog(@"Supported languages: %@", [AIBudsAISDK allSupportedLanguagesForVendor:vendor]);Проверка требований авторизации
После настройки AI-данных подключённого устройства авторизуйте поставщиков, режим которых инициируется приложением.
- Swift
- Objective-C
let vendor = AIBudsAISDK.aiServiceVendor
if AIBudsAISDK.authenticationMode(for: vendor) == .appInitiated,
!AIBudsAISDK.isAuthenticated(for: vendor)
{
AIBudsAISDK.authenticateDevice(deviceInfo) { success, error in
guard success else {
print(error?.localizedDescription ?? "Authentication failed")
return
}
print("AI provider authenticated")
}
}AIBudsAIServiceVendor vendor = AIBudsAISDK.aiServiceVendor;
if ([AIBudsAISDK authenticationModeForVendor:vendor] == AIBudsAIAuthenticationModeAppInitiated &&
![AIBudsAISDK isAuthenticatedForVendor:vendor]) {
[AIBudsAISDK
authenticateDevice:deviceInfo
completion:^(BOOL success, NSError *error) {
if (!success) {
NSLog(@"%@", error.localizedDescription ?: @"Authentication failed");
return;
}
NSLog(@"AI provider authenticated");
}];
}Примечания
setAIServiceVendor(_:)не регистрирует и не устанавливает SDK поставщика.- При выборе
.noneу операций, зависящих от AI-сервисов, отсутствует рабочий поставщик. - Повторный вызов
initialize(_:)возвращаетfalseи сохраняет существующую инициализацию. - Если несколько реализаций объявляют одно значение enum поставщика, сохраняется первая зарегистрированная реализация.
- Поддерживаемые функции и языки могут различаться у разных поставщиков.