iOS SDK
Use the iOS NUI SDK to stream recorded audio to Intelligent Speech Interaction and receive recognition results through callbacks. This topic describes SDK integration, the calling sequence, code examples, and key APIs.
Prerequisites
Activate Intelligent Speech Interaction and obtain a project Appkey. For project configuration, see Manage projects.
Obtain an NLS token. For instructions, see Obtain a token.
Keep the AccessKey ID and AccessKey secret on your server. Do not include them in app code or store them on a mobile device. Cloud-based real-time speech recognition uses an Appkey and an NLS token for authentication. Obtain the token on your server, send it to the app, and refresh it before it expires.
Download and integrate the SDK
Download an iOS NUI SDK package that supports real-time speech recognition from Select and download a mobile SDK.
The integration instructions and examples use the V2.7.4-01B-20260904_iOS_TLS package. The SDK does not provide a CocoaPods integration package; integrate it manually. The iOS APIs after version 2.5.14 use Objective-C and no longer require a C++ hybrid interface.
-
Extract the SDK package and select the build for the target platform.
Build
Use
Release/nuisdk.xcframeworkRecommended for physical devices and simulators on Apple Silicon Macs. Contains separate iOS arm64 and iOS Simulator arm64 variants.
Release/nuisdk.frameworkContains arm64 for physical devices and x86_64 for simulators on Intel Macs. Remove simulator architectures from device distribution builds.
Release-iphoneos/nuisdk.xcframeworkContains only arm64 for physical devices.
Add the selected Framework or XCFramework to the Xcode project. Add it under Build Phases > Link Binary With Libraries for the target, and select Embed & Sign under General > Frameworks, Libraries, and Embedded Content.
-
Import the SDK header:
#import <nuisdk/NeoNui.h> Add
NSMicrophoneUsageDescriptiontoInfo.plistto describe why the app uses the microphone. Obtain microphone permission before recording. The recording module must configure and activateAVAudioSession.
The bundled demo project includes utilities for recording, playback, and file operations. SpeechTranscriberViewController demonstrates real-time speech recognition and uses AudioController for recording. Replace the Appkey and token to run the demo. The Framework includes Resources.bundle. Starting with SDK 2.6.2, cloud-only recognition does not require the workspace resource directory parameter.
Calling sequence
Create the SDK and recorder instances, assign their delegates, and initialize the SDK.
Call
nui_set_paramsto configure recognition. Setservice_typetoSERVICE_TYPE_SPEECH_TRANSCRIBER.Call
nui_dialog_start:MODE_P2Tto start recognition.Control recording in
onNuiAudioStateChangedand provide audio inonNuiNeedAudioData.Obtain intermediate and sentence results from
EVENT_ASR_PARTIAL_RESULTandEVENT_SENTENCE_END.Call
nui_dialog_cancel:NOto stop recognition normally. Wait for the task to end, then callnui_releaseto release SDK resources.
Code examples
The following example uses AudioController.h and AudioController.m from the demo to record 16 kHz, 16-bit, mono PCM audio. Add the helper class and its dependencies to the project, then configure, start, and stop recognition in order. Initialization may block, so run it off the UI thread. Call control methods sequentially for each SDK instance.
Use [NeoNui get_instance] to obtain the default singleton or [[NeoNui alloc] init] to create an instance. The following example uses the latter.
Configure the gateway
NSString *gateway = @"wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1";
Initialization, recognition, and callbacks
#import <Foundation/Foundation.h>
#import <nuisdk/NeoNui.h>
#import "AudioController.h"
@interface SpeechRecognizer : NSObject <NeoNuiSdkDelegate, ConvVoiceRecorderDelegate>
@property(nonatomic, strong) NeoNui *nui;
@property(nonatomic, strong) AudioController *recorder;
@property(nonatomic, strong) NSMutableData *audioBuffer;
@property(atomic) BOOL finished;
@property(nonatomic, copy) void (^onFinished)(void);
- (int)configureWithAppkey:(NSString *)appkey token:(NSString *)token
gateway:(NSString *)gateway;
- (int)start;
- (int)stop;
- (int)releaseSdk;
@end
@implementation SpeechRecognizer
- (NSString *)jsonString:(NSDictionary *)value {
NSData *data = [NSJSONSerialization dataWithJSONObject:value options:0 error:nil];
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
- (int)configureWithAppkey:(NSString *)appkey token:(NSString *)token
gateway:(NSString *)gateway {
self.audioBuffer = [NSMutableData data];
self.finished = YES;
self.nui = [[NeoNui alloc] init];
self.nui.delegate = self;
self.recorder = [[AudioController alloc] init:only_recorder recorderSampleRate:16000];
self.recorder.delegate = self;
NSDictionary *initParams = @{
@"app_key": appkey,
@"token": token,
@"url": gateway,
@"device_id": [[NSUUID UUID] UUIDString],
@"service_mode": @"1"
};
int code = [self.nui nui_initialize:[self jsonString:initParams].UTF8String
logLevel:NUI_LOG_LEVEL_VERBOSE saveLog:NO];
if (code != 0) {
return code;
}
NSDictionary *params = @{
@"service_type": @(SERVICE_TYPE_SPEECH_TRANSCRIBER),
@"nls_config": @{
@"sample_rate": @16000,
@"enable_intermediate_result": @YES
}
};
code = [self.nui nui_set_params:[self jsonString:params].UTF8String];
return code;
}
- (int)start {
@synchronized(self) {
[self.audioBuffer setLength:0];
}
self.finished = NO;
int code = [self.nui nui_dialog_start:MODE_P2T dialogParam:"{}"];
if (code != 0) {
self.finished = YES;
}
return code;
}
- (int)stop {
return [self.nui nui_dialog_cancel:NO];
}
- (int)releaseSdk {
[self.recorder stopRecorder:NO];
int code = [self.nui nui_release];
self.nui.delegate = nil;
self.recorder.delegate = nil;
return code;
}
- (void)voiceRecorded:(unsigned char *)buffer Length:(int)len {
@synchronized(self) {
[self.audioBuffer appendBytes:buffer length:len];
}
}
- (int)onNuiNeedAudioData:(char *)audioData length:(int)len {
@synchronized(self) {
NSUInteger count = MIN((NSUInteger)len, self.audioBuffer.length);
if (count == 0) {
return 0;
}
memcpy(audioData, self.audioBuffer.bytes, count);
[self.audioBuffer replaceBytesInRange:NSMakeRange(0, count)
withBytes:NULL length:0];
return (int)count;
}
}
- (void)onNuiAudioStateChanged:(NuiAudioState)state {
if (state == STATE_OPEN) {
[self.recorder startRecorder];
} else if (state == STATE_PAUSE || state == STATE_CLOSE) {
[self.recorder stopRecorder:NO];
}
}
- (void)onNuiEventCallback:(NuiCallbackEvent)event dialog:(long)dialog
kwsResult:(const char *)wuw asrResult:(const char *)result
ifFinish:(BOOL)finish retCode:(int)code {
if (event == EVENT_ASR_PARTIAL_RESULT || event == EVENT_SENTENCE_END) {
if (result != NULL) {
NSLog(@"Recognition result: %s", result);
}
} else if (event == EVENT_ASR_ERROR) {
NSLog(@"Recognition error: %d, %s", code, result ?: "");
const char *response = [self.nui nui_get_all_response];
if (response != NULL) {
NSLog(@"Error response: %s", response);
}
} else if (event == EVENT_MIC_ERROR) {
NSLog(@"Audio input error");
}
if (finish) {
self.finished = YES;
if (self.onFinished) {
self.onFinished();
}
}
}
- (void)onNuiRmsChanged:(float)rms {}
- (void)recorderDidStart {}
- (void)recorderDidStop {}
- (void)voiceDidFail:(NSError *)error {
NSLog(@"Recorder error: %@", error);
}
- (void)playerDidStart {}
- (void)playerDrainDataFinish {}
- (void)playerDidFinish {}
- (void)playSoundLevel:(int)level {}
- (void)playData:(unsigned char *)buffer Length:(int)len {}
@end
Keep a SpeechRecognizer instance in the app. After obtaining microphone permission, use the following code to initialize and start recognition. Your application server supplies appkey and token; use the gateway configured above.
SpeechRecognizer *recognizer = [[SpeechRecognizer alloc] init];
dispatch_queue_t controlQueue = dispatch_queue_create("speech.control", DISPATCH_QUEUE_SERIAL);
__weak SpeechRecognizer *weakRecognizer = recognizer;
recognizer.onFinished = ^{
dispatch_async(controlQueue, ^{
[weakRecognizer releaseSdk];
});
};
dispatch_async(controlQueue, ^{
int code = [recognizer configureWithAppkey:appkey token:token gateway:gateway];
if (code == 0) {
code = [recognizer start];
}
if (code != 0) {
NSLog(@"SDK call failed: %d", code);
[recognizer releaseSdk];
}
});
device_id identifies a device or app instance. A unique identifier is recommended for troubleshooting. The example generates an application UUID. To keep the identifier across app launches, store and reuse it in the app.
Do not call SDK control methods, such as initialization, start, stop, or release, from event callbacks, because this can cause a deadlock. Use nui_get_all_response in the current event callback to retrieve the full response. Dispatch UI updates to the main thread.
Stop recognition and release resources
To stop recognition, call stop on the same control queue. When the task completes or encounters an error, the callback sets finish to YES. The example uses onFinished to dispatch resource release to the control queue rather than releasing resources directly on the event callback thread.
dispatch_async(controlQueue, ^{
int code = [recognizer stop];
if (code != 0) {
NSLog(@"Stop failed: %d", code);
}
});
nui_dialog_cancel:NO waits for normal completion. Stopping does not guarantee a sentence result: a task with no valid speech can complete without producing EVENT_SENTENCE_END.
Set and update parameters
Place recognition parameters in nls_config and set service_type to SERVICE_TYPE_SPEECH_TRANSCRIBER. enable_intermediate_result is optional and enables intermediate results. Configure the following optional settings as needed; they do not all need to be enabled. Use this snippet to replace the code that builds params and calls nui_set_params in configureWithAppkey.
NSMutableDictionary *nlsConfig = [NSMutableDictionary dictionary];
nlsConfig[@"enable_intermediate_result"] = @YES;
nlsConfig[@"enable_punctuation_prediction"] = @YES;
nlsConfig[@"enable_inverse_text_normalization"] = @YES;
// nlsConfig[@"enable_voice_detection"] = @YES;
// nlsConfig[@"max_start_silence"] = @10000;
// nlsConfig[@"max_end_silence"] = @800;
// nlsConfig[@"max_sentence_silence"] = @800;
// nlsConfig[@"enable_words"] = @NO;
// nlsConfig[@"sample_rate"] = @16000;
// nlsConfig[@"sr_format"] = @"opus";
NSDictionary *params = @{
@"nls_config": nlsConfig,
@"service_type": @(SERVICE_TYPE_SPEECH_TRANSCRIBER)
};
NSData *data = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
code = [self.nui nui_set_params:json.UTF8String];
For initialization fields and SDK parameters such as direct_ip and extend_config, see the Mobile SDK API reference. Use direct_ip to set an address when using HttpDNS. Use extend_config to pass supported SDK extension parameters that do not have dedicated fields.
For recognition request parameters, see the Real-time speech recognition API reference.
To update the Appkey or token before recognition starts, add the following method and its declaration to SpeechRecognizer, and use startWithAppkey:token: instead of start. To run multiple sessions on the same initialized instance, release resources after all sessions rather than in onFinished after each session. If the corresponding temporary parameters are not set for the next session, the SDK uses the values supplied during initialization.
- (int)startWithAppkey:(NSString *)appkey token:(NSString *)updatedToken {
@synchronized(self) {
[self.audioBuffer setLength:0];
}
self.finished = NO;
NSDictionary *dialogParams = @{@"app_key": appkey, @"token": updatedToken};
NSString *json = [self jsonString:dialogParams];
int code = [self.nui nui_dialog_start:MODE_P2T dialogParam:json.UTF8String];
if (code != 0) {
self.finished = YES;
}
return code;
}
Key APIs and callbacks
SDK APIs
Initialization, parameter configuration, recognition control, and release APIs return NuiResultCode. A return value of 0 indicates a successful call. Recognition results and task status are delivered through callbacks.
Initialization and parameters
nui_initialize: parameters is the initialization JSON string. level is the log level; smaller values produce more detailed logs. save_log controls whether logs are saved to debug_path. Release resources before reinitializing the same instance. Run initialization off the UI thread.
- (NuiResultCode)nui_initialize:(const char *)parameters
logLevel:(NuiSdkLogLevel)level saveLog:(BOOL)save_log;
When saving logs, ensure that debug_path exists and is writable, and manage the storage used by log files. When save_log is enabled, save_wav controls whether audio debug files are saved to the debug directory.
nui_set_params: Sets SDK and recognition parameters as a JSON string.
- (NuiResultCode)nui_set_params:(const char *)params;
Recognition control and release
nui_dialog_start: Starts recognition. Use MODE_P2T for real-time recognition. dialog_params can contain temporary parameters for the current session; pass an empty JSON object if none are needed. Enable the corresponding options in nls_config to use online VAD.
- (NuiResultCode)nui_dialog_start:(NuiVadMode)vad_mode
dialogParam:(const char *)dialog_params;
nui_dialog_cancel: force=NO stops audio input and waits for normal completion. force=YES ends the session immediately without waiting for the final result.
- (NuiResultCode)nui_dialog_cancel:(BOOL)force;
nui_release: Releases SDK resources.
- (NuiResultCode)nui_release;
Version and response queries
nui_get_version: Returns the SDK version string.
- (const char *)nui_get_version;
nui_get_all_response: Returns the full JSON string for the current event when called from the event callback.
- (const char *)nui_get_all_response;
NeoNuiSdkDelegate callbacks
onNuiEventCallback: The SDK event callback. dialog is the session identifier and is not currently used. wuw is for wake-word recognition and is not used in this scenario. asr_result contains recognition results or error information. finish indicates that the current task has ended. code provides the error code for EVENT_ASR_ERROR. Keep the task_id from the response for troubleshooting.
- (void)onNuiEventCallback:(NuiCallbackEvent)nuiEvent
dialog:(long)dialog kwsResult:(const char *)wuw
asrResult:(const char *)asr_result
ifFinish:(BOOL)finish retCode:(int)code;
|
Event |
Description |
|
|
A speech starting point is detected. |
|
|
A speech ending point is detected. |
|
|
An intermediate recognition result. |
|
|
A final speech recognition result event. |
|
|
A recognition error. Use the error code to determine the cause. |
|
|
A recording error: the SDK has received no audio for 2 consecutive seconds. Check recording and audio delivery. |
|
|
The start of a sentence is detected during real-time recognition. |
|
|
The end of a sentence is detected and its complete result is returned. |
|
|
Not currently used. |
|
|
Reports task completion after real-time recognition stops. |
onNuiNeedAudioData: Called continuously after recognition starts. The app fills audioData with audio; len is the requested number of bytes. Return the number of bytes actually supplied.
- (int)onNuiNeedAudioData:(char *)audioData length:(int)len;
onNuiAudioStateChanged: Instructs the app to control recording. Start recording on STATE_OPEN, and stop on STATE_PAUSE or STATE_CLOSE.
- (void)onNuiAudioStateChanged:(NuiAudioState)state;
onNuiRmsChanged: Reports the audio energy value, ranging from -160 to 0.
- (void)onNuiRmsChanged:(float)rms;
FAQ
Can the Android and iOS SDKs be used in a private cloud?
The mobile SDKs can call public-cloud ASR and TTS services and can also be used in a private cloud. Private-cloud installation packages do not include the mobile SDKs by default. Download them from the SDK documentation for the corresponding service in the help center.
Does iOS support background processing?
The SDK does not restrict foreground or background use. Background recording also requires the app to enable the appropriate capability and keep the recorder and audio session active. To integrate background recording:
In Required background modes in
Info.plist, add App plays audio or streams audio/video using AirPlay, which corresponds to theaudiovalue inUIBackgroundModes.Check how the recording module handles entering the background. If using
NLSVoiceRecorder.mfrom an older demo, remove theAudioSessionSetActive(NO)call in_appResignActiveso that the audio session remains active. The current package usesAudioController; manage recording and audio sessions according to that module's implementation.
- (void)_appResignActive {
_inBackground = true;
// AudioSessionSetActive(NO);
}
How do I resolve no suitable image found on a physical device?
Use the full error message to check that the Framework contains a device architecture, is embedded in the app, and has a matching signature and provisioning profile. For the current package, use an XCFramework with a device variant. After correcting the configuration, you can remove the old app from the device, select Product > Clean Build Folder in Xcode, and rebuild and install the app. For signing errors, correct the signing configuration and repackage the app.
How do I resolve EVENT_MIC_ERROR?
Check microphone permission, whether another module is using the recording device, and whether the recording module continuously supplies audio. Ensure that onNuiNeedAudioData returns the actual number of bytes supplied and that the audio format matches the recognition parameters.
How do I resolve errors when importing NeoNui.h?
Confirm that the SDK is added to the project and check the Framework search paths. Import the header with #import <nuisdk/NeoNui.h>. Add the dynamic library to Link Binary With Libraries and select Embed & Sign.
How do I resolve built for iOS + iOS Simulator errors or a requirement to use Legacy Build System?
This issue involves older Framework packages that combine device and simulator architectures. Prefer an XCFramework with separate platform variants and select the build for the target platform.
Older packages and Xcode versions
If you continue using an older Framework and your Xcode version provides Validate Workspace, you can set it to Yes and rebuild. This workaround applies to older integration methods. Current XCFramework integration does not require switching to Legacy Build System.
How do I resolve undefined std::__1::mutex symbols in a Flutter project?
These symbols belong to the C++ runtime. Check that the iOS target links libc++ and that static libraries containing C++ code and their dependencies are added to the linking phase. You can add libc++.tbd under Link Binary With Libraries. The build architecture must also match the target platform.
How do I resolve microphone conflicts when using TRTC and speech recognition together?
Use one recording module to capture audio and supply it to the SDKs that need it, avoiding competition for the microphone. Supply PCM audio that meets recognition requirements through NUI's onNuiNeedAudioData callback. For TRTC, use the audio input APIs in its native iOS SDK.
How do I resolve Unsupported Architectures during App Store submission?
A device app submitted for distribution must not include simulator architectures such as x86_64 or i386. Prefer an XCFramework so that the build selects the device variant. If using an older Framework that contains simulator architectures, inspect its executable and remove simulator architectures from the distribution build:
lipo -info /path/to/nuisdk.framework/nuisdk
Run lipo on the executable inside the Framework. An XCFramework stores platform variants separately; select the variant for the target platform.