Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 60 additions & 9 deletions sdks/ios/deliteAI/Classes/sources/NimbleNetApi.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,42 @@
import Foundation
import SwiftProtobuf

/// The main entry point for the NimbleNet iOS SDK.
///
/// `NimbleNetApi` provides a high-level interface for integrating AI/ML capabilities
/// and event processing into your iOS applications. This class manages the SDK's lifecycle,
/// including initialization, session management, running local inference for AI/ML models,
/// and processing user events.
///
/// Developers can use `NimbleNetApi` to:
/// - **Initialize the SDK**: Configure the SDK with necessary credentials and settings.
/// - **Manage Sessions**: Control the active session for event processing and model interactions.
/// - **Run AI/ML Models**: Execute AI/ML models with custom inputs to get predictions or insights.
/// - **Add Events**: Process user interactions and other relevant data for analytics or model improvement.
/// - **Check Readiness**: Determine if the SDK and its underlying models are ready for operations.
///
/// This class abstracts away the complexities of model loading, data handling, and native
/// interoperability, providing a clean and consistent API for mobile developers.
public class NimbleNetApi{

private static let nimbleNetController: NimbleNetController = NimbleNetController();

/// Restarts the current session.
public static func restartSession(){
nimbleNetController.restartSession()
}

/// Restarts the session with a specific session identifier.
/// - Parameter sessionId: The ID for the new session.
public static func restartSessionWithId(sessionId: String){
nimbleNetController.restartSession(withId: sessionId)
}

/// Initializes the NimbleNet SDK with the provided configuration.
/// - Parameters:
/// - config: The configuration object.
/// - assetsJson: Optional JSON array for asset configuration. This is mandatory for offline initialization.
/// - Returns: A `NimbleNetResult<Void>` indicating success or failure.
public static func initialize(config:NimbleNetConfig, assetsJson: [[String: Any]]? = nil)->NimbleNetResult<Void>{

var config = config
Expand Down Expand Up @@ -64,6 +90,11 @@ public class NimbleNetApi{

}

/// Initializes the NimbleNet SDK with a JSON string configuration.
/// - Parameters:
/// - config: The configuration as a JSON string.
/// - assetsJson: Optional JSON array for asset configuration. This is mandatory for offline initialization.
/// - Returns: A `NimbleNetResult<Void>` indicating success or failure.
public static func initialize(config:String, assetsJson: [[String: Any]]?) -> NimbleNetResult<Void>{

if let jsonData = config.data(using: .utf8) {
Expand All @@ -83,6 +114,11 @@ public class NimbleNetApi{
}
}

/// Adds an event with dictionary-based data.
/// - Parameters:
/// - events: A dictionary containing event data.
/// - eventType: The type of event.
/// - Returns: A `NimbleNetResult<UserEventdata>` with the result of adding the event.
public static func addEvent(events: [String: Any], eventType: String) -> NimbleNetResult<UserEventdata> {

do {
Expand All @@ -100,12 +136,19 @@ public class NimbleNetApi{
}
}

/// Adds an event with a JSON string payload.
/// - Parameters:
/// - eventString: The event data as a JSON string.
/// - eventType: The type of event.
/// - Returns: A `NimbleNetResult<UserEventdata>` with the result of adding the event.
public static func addEvent(eventString: String, eventType: String) -> NimbleNetResult<UserEventdata> {
let res = nimbleNetController.add_event_controller(eventString, eventType:eventType)!
return NimbleNetResult<UserEventdata>(data: NSDictionary(dictionary:res))

}


/// Checks if the NimbleNet SDK is ready.
/// - Returns: A `NimbleNetResult<Unit>` indicating the readiness status.
public static func isReady() -> NimbleNetResult<Unit>
{
do{
Expand All @@ -118,6 +161,11 @@ public class NimbleNetApi{
}
}

/// Runs a specified method with provided inputs.
/// - Parameters:
/// - methodName: The name of the method to run.
/// - inputs: A dictionary of input tensors.
/// - Returns: A `NimbleNetResult<NimbleNetOutput>` containing the method's output.
public static func runMethod(methodName: String, inputs: [String: NimbleNetTensor]) -> NimbleNetResult<NimbleNetOutput> {

do {
Expand Down Expand Up @@ -180,7 +228,7 @@ public class NimbleNetApi{
func convertToDictionary(_ input: NimbleNetTensor) -> [String: Any] {
if(input.datatype.rawValue == DataType.FE_OBJ.rawValue){
var message = input.data as! (Message & _ProtoNameProviding)
var wrapper = ProtoObjectWrapper(message: message)
var wrapper = ProtoObjectWrapper(message: message)
return [
"data": wrapper,
"type": input.datatype.value,
Expand All @@ -197,6 +245,8 @@ public class NimbleNetApi{
}

//utils
/// Creates the NimbleNet SDK directory.
/// - Returns: The path to the created directory.
private static func createNimbleNetDirectory() -> String {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
fatalError("Failed to get documents directory.")
Expand All @@ -215,13 +265,12 @@ public class NimbleNetApi{
return folderURL.path
}

private static func convertToVoidPointer<T>(_ value: T) -> UnsafeMutableRawPointer {
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: value)
return UnsafeMutableRawPointer(pointer)
}


/// Populates a `NimbleNetResult` with error information.
/// - Parameters:
/// - errorCode: The error code.
/// - errorMessage: The error message.
/// - Returns: A `NimbleNetResult<T>` with error details.
private static func populateNimbleNetResultWithError<T>(errorCode:Int,errorMessage:String) -> NimbleNetResult<T>{
let dict: NSDictionary = [
"status": false,
Expand All @@ -236,7 +285,9 @@ public class NimbleNetApi{

}


/// Verifies the types and shapes of user-provided inputs for model execution.
/// - Parameter inputs: A dictionary of input tensors to verify.
/// - Throws: `DataTypeMismatchError` if any input data type or shape is invalid.
func verifyUserInputs(inputs: [String: NimbleNetTensor]) throws {
for (_, modelInput) in inputs {
let data = modelInput.data
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,75 @@
* SPDX-License-Identifier: Apache-2.0
*/

import Foundation
import SwiftProtobuf

/// Configuration class for initializing the NimbleNet SDK.
///
/// This class contains all the necessary parameters and settings required to initialize and
/// configure the NimbleNet SDK. It includes authentication credentials, server endpoints, resource
/// limits, and deployment options.
public struct NimbleNetConfig: Codable {

/// Your unique client identifier from NimbleNet platform. Must be a non-empty
/// string obtained from your NimbleNet account.
public let clientId: String

/// Authentication secret key for API access. Keep this value secure and never
/// expose it in logs or client-side code.
public let clientSecret: String

/// The base URL of the NimbleNet platform API endpoint. Must be a valid HTTPS URL (e.g.,
/// "https://api.nimblenet.ai").
public let host: String

/// Unique identifier for this device or application installation. Can be a UUID,
/// device fingerprint, or custom identifier. Should remain consistent across app sessions for the
/// same device.
public let deviceId: String

/// Enable debug mode for detailed logging and diagnostics. Set to `false` in production
/// builds for optimal performance.
public let debug: Bool

/// Version identifier for API compatibility checking. Should match your
/// application version or SDK compatibility version. Used to ensure client-server API
/// compatibility.
public var compatibilityTag: String

/// Optional custom session identifier for session management. If empty, the SDK
/// will generate a default session ID. Useful for multi-user applications or session persistence.
public var sessionId: String

/// Optional maximum database size limit in kilobytes. When reached, older data
/// may be purged to stay within limits. Set based on your device storage constraints.
public var maxDBSizeKBs: Float?

/// Optional maximum event data storage limit in kilobytes. Controls how much
/// event data can be cached before upload.
public var maxEventsSizeKBs: Float?

/// Array of cohort identifiers for A/B testing and experimentation. Used to assign
/// users to specific test groups or feature variants.
public var cohortIds: [String]

/// Whether the assets will be downloaded from cloud or they are
/// already bundled with the app.
public var online: Bool

/// Initializes a `NimbleNetConfig` instance.
/// - Parameters:
/// - clientId: Your unique client identifier from NimbleNet platform. Defaults to an empty string.
/// - clientSecret: Authentication secret key for API access. Defaults to an empty string.
/// - host: The base URL of the SaaS Configuration platform API endpoint. Defaults to an empty string.
/// - deviceId: Unique identifier for this device or application installation. Defaults to an empty string.
/// - debug: Enable debug mode for detailed logging and diagnostics. Defaults to `false`.
/// - compatibilityTag: Version identifier for API compatibility checking. Defaults to an empty string.
/// - sessionId: Optional custom session identifier for session management. Defaults to an empty string.
/// - maxDBSizeKBs: Optional maximum database size limit in kilobytes. Defaults to `nil`.
/// - maxEventsSizeKBs: Optional maximum event data storage limit in kilobytes. Defaults to `nil`.
/// - cohortIds: Array of cohort identifiers for A/B testing and experimentation. Defaults to an empty array.
/// - online: Whether the assets will be downloaded from cloud or they are already bundled with the app. Defaults to `false`.
public init(clientId: String = "",
clientSecret: String = "",
host: String = "",
Expand Down
Loading