### Example Usage Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/bridgeSettingsConfig.md An example demonstrating how to use BridgeSettingsConfig to configure build settings. ```APIDOC ## Example Usage ### Description This example shows how to configure C, C++, Swift, and linker settings using the `bridgeSettings` block. ### Code ```kotlin bridgeSettings { cSetting { defines = listOf(Pair("C_DEBUG", "2")) headerSearchPath = listOf("./includes/") unsafeFlags = listOf("-W") } cxxSetting { defines = listOf(Pair("CXX_DEBUG", "1")) headerSearchPath = listOf("./includes/") unsafeFlags = listOf("-W") } linkerSetting { linkedFramework = listOf("UIKit") linkedLibrary = listOf("-W") unsafeFlags = listOf("-W") } swiftSettings { defines = listOf("CUSTOM_DEFINE") enableExperimentalFeature = "CImplementation" enableUpcomingFeature = "ExistentialAny" interoperabilityMode = "Cxx" } } ``` ``` -------------------------------- ### Add User Setup Hint for Linker Errors Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Provide a custom message appended to linker errors to help users resolve them. Example suggests adding a framework to Xcode. ```kotlin userSetupHint = "Add the XYZ framework to your Xcode project's linked libraries." ``` -------------------------------- ### Package.swift Manifest Example Source: https://github.com/frankois944/spm4kmp/blob/main/docs/usages/largebridge.md Defines the structure, products, and dependencies of a Swift Package. Ensure the swift-tools-version matches your project requirements. ```swift // swift-tools-version: 5.9 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "MyStripeSDK", platforms: [.iOS(.v14)], products: [ // Products define the executables and libraries a package produces, making them visible to other packages. .library( name: "MyStripeSDK", targets: ["MyStripeSDK"]), ], dependencies: [ .package(url: "https://github.com/stripe/stripe-ios-spm", .upToNextMajor(from: "24.5.0")), ], targets: [ // Targets are the basic building blocks of a package, defining a module or a test suite. // Targets can depend on other targets in this package and products from dependencies. .target( name: "MyStripeSDK", dependencies: [ .product(name: "Stripe", package: "stripe-ios-spm"), .product(name: "StripePaymentSheet", package: "stripe-ios-spm") ]), .testTarget( name: "MyStripeSDKTests", dependencies: [ "MyStripeSDK" ] ), ] ) ``` -------------------------------- ### Configure Swift Bridge Settings Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Set up compiler and linker settings for the Swift bridge. This example enables experimental Swift concurrency features. ```kotlin bridgeSettings { swiftSettings { unsafeFlags("-enable-experimental-feature", "StrictConcurrency") } } ``` -------------------------------- ### Configure Bridge Settings Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/bridgeSettingsConfig.md Example demonstrating how to configure C, C++, linker, and Swift build settings for a target. This is useful for setting up cross-language compilation and interoperability. ```kotlin bridgeSettings { cSetting { defines = listOf(Pair("C_DEBUG", "2")) headerSearchPath = listOf("./includes/") unsafeFlags = listOf("-W") } cxxSetting { defines = listOf(Pair("CXX_DEBUG", "1")) headerSearchPath = listOf("./includes/") unsafeFlags = listOf("-W") } linkerSetting { linkedFramework = listOf("UIKit") linkedLibrary = listOf("-W") unsafeFlags = listOf("-W") } swiftSettings { defines = listOf("CUSTOM_DEFINE") enableExperimentalFeature = "CImplementation" enableUpcomingFeature = "ExistentialAny" interoperabilityMode = "Cxx" } } ``` -------------------------------- ### Swift Package Source Code Example Source: https://github.com/frankois944/spm4kmp/blob/main/docs/usages/largebridge.md Swift code for a local package must be marked with @objcMembers and have public visibility to be accessible from Kotlin. This example initializes Stripe's PaymentSheet. ```swift import StripePaymentSheet @objcMembers public class MyStripeSDK: NSObject { private var paymentSheet: PaymentSheet? private var paymentIntentClientSecret: String private let backendCheckoutUrl = URL(string: "Your backend endpoint/payment-sheet") public init(paymentIntentClientSecret: String) { self.paymentIntentClientSecret = paymentIntentClientSecret } public func doStripeJob() { var configuration = PaymentSheet.Configuration() configuration.merchantDisplayName = "Example, Inc." self.paymentSheet = PaymentSheet(paymentIntentClientSecret: self.paymentIntentClientSecret, configuration: configuration) } } ``` -------------------------------- ### Legacy Swift Package Configuration (< 1.1.0) Source: https://github.com/frankois944/spm4kmp/blob/main/docs/bridge.md Legacy Gradle configuration for Swift Package setup prior to version 1.1.0. Use this only if you are on an older version of the plugin. ```kotlin swiftPackageConfig { create("[cinteropName]") { } } ``` -------------------------------- ### Accessing Bundled Resources in Swift Source: https://github.com/frankois944/spm4kmp/blob/main/docs/bridge.md Example of how to access resources bundled with the Swift bridge using `Bundle.module`. Ensure the resource file exists in the appropriate `Resources-*` folder. ```swift let url = Bundle.module.url(forResource: "bridgeString", withExtension: "txt") ``` -------------------------------- ### Configure Exported Package Settings Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Define settings for the generated local Swift package for Xcode integration. This example includes the 'FirebaseCore' product. ```kotlin exportedPackageSettings { includeProduct("FirebaseCore") } ``` -------------------------------- ### Configure Additional Linker Flags Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Specify extra linker flags for cinterop processing. Example includes linking the 'Security' framework. ```kotlin linkerOpts = listOf("-lz", "-framework", "Security") ``` -------------------------------- ### Access Exported Swift Methods and Properties from Kotlin Source: https://github.com/frankois944/spm4kmp/blob/main/docs/bridge.md Example demonstrating how to import and use methods and properties exported from Swift into Kotlin code. Ensure the `cinteropName` matches your Gradle configuration. ```kotlin import [cinteropName].MySwiftBridge val contentFromSwift = MySwiftBridge().exportedMethod() val aView = MySwiftBridge().exportedView() as UIView ``` -------------------------------- ### Local Package Message Example Source: https://github.com/frankois944/spm4kmp/blob/main/docs/bridgeWithDependencies.md This message indicates that a dependency needs to be added to your Xcode project as a local package. A local Swift package will be generated automatically. ```text Spm4Kmp: The following dependencies [some_dependency_name] need to be added to your Xcode project. A local Swift package has been generated at /path/to/the/local/package Please add it to your Xcode project as a local package dependency. ``` -------------------------------- ### Swift Bridge for Player Controller Source: https://context7.com/frankois944/spm4kmp/llms.txt Create a Swift class with `@objcMembers` to act as a bridge for Kotlin/Native. This example exposes a player controller with methods to set media items and manage the player's lifecycle, making it accessible from Kotlin. ```swift import Foundation import KSPlayer @objcMembers public class PlayerController: NSObject { private let player = IOSVideoPlayerView() override public init() { super.init() KSOptions.secondPlayerType = KSMEPlayer.self player.contentMode = .scaleAspectFill } public func setMediaItem(videoUrl: URL) { player.set(url: videoUrl, options: KSOptions()) } public var playerView: NSObject { player } public func releasePlayer() { player.resetPlayer() player.removeFromSuperview() } } ``` -------------------------------- ### Swift Bridge for MD5 Hashing Source: https://github.com/frankois944/spm4kmp/blob/main/docs/bridgeWithDependencies.md Implement a Swift class annotated with `@objcMembers` and `public` to expose functionality to Kotlin. This example demonstrates an MD5 hashing function using the CryptoSwift library. ```swift import Foundation import CryptoSwift @objcMembers public class MySwiftBridge: NSObject { public func toMD5(value: String) -> String { return value.md5() } } ``` -------------------------------- ### Configure Cinterop Compiler and Linker Flags Source: https://context7.com/frankois944/spm4kmp/llms.txt Pass additional compiler and linker flags for cinterop processing. Configure strict and non-strict enums, exception handling modes, and designated initializer checks. Provide custom user setup hints. ```kotlin // build.gradle.kts kotlin { iosArm64 { swiftPackageConfig(cinteropName = "nativeBridge") { compilerOpts = listOf("-DDEBUG=1", "-fmodules") linkerOpts = listOf("-lz", "-framework", "Security", "-framework", "CoreFoundation") // Cinterop enum configuration strictEnums = listOf("MyObjCEnum", "AnotherEnum") nonStrictEnums = listOf("NSStringEncoding") // Exception handling foreignExceptionMode = "objc-wrap" // Initializer checks disableDesignatedInitializerChecks = true // Custom error hints userSetupHint = "Add the XYZ framework to your Xcode project's linked libraries." } } } ``` -------------------------------- ### HevSocks5Tunnel Headers Source: https://github.com/frankois944/spm4kmp/blob/main/docs/usages/importCLangFramework.md This C header file defines the interface for the HevSocks5Tunnel, including functions for starting, stopping, and retrieving statistics for the socks5 tunnel. It is used when importing the framework. ```cpp /* ============================================================================ Name : hev-main.h Author : hev Copyright : Copyright (c) 2019 - 2023 hev Description : Main ============================================================================ */ #ifndef __HEV_MAIN_H__ #define __HEV_MAIN_H__ #include #ifdef __cplusplus extern "C" { #endif /** * hev_socks5_tunnel_main: * @config_path: config file path * @tun_fd: tunnel file descriptor * * Start and run the socks5 tunnel, this function will blocks until the * hev_socks5_tunnel_quit is called or an error occurs. * * Returns: returns zero on successful, otherwise returns -1. * * Since: 2.4.6 */ int hev_socks5_tunnel_main (const char *config_path, int tun_fd); /** * hev_socks5_tunnel_main_from_file: * @config_path: config file path * @tun_fd: tunnel file descriptor * * Start and run the socks5 tunnel, this function will blocks until the * hev_socks5_tunnel_quit is called or an error occurs. * * Returns: returns zero on successful, otherwise returns -1. * * Since: 2.6.7 */ int hev_socks5_tunnel_main_from_file (const char *config_path, int tun_fd); /** * hev_socks5_tunnel_main_from_str: * @config_str: string config * @config_len: the byte length of string config * @tun_fd: tunnel file descriptor * * Start and run the socks5 tunnel, this function will blocks until the * hev_socks5_tunnel_quit is called or an error occurs. * * Returns: returns zero on successful, otherwise returns -1. * * Since: 2.6.7 */ int hev_socks5_tunnel_main_from_str (const unsigned char *config_str, unsigned int config_len, int tun_fd); /** * hev_socks5_tunnel_quit: * * Stop the socks5 tunnel. * * Since: 2.4.6 */ void hev_socks5_tunnel_quit (void); /** * hev_socks5_tunnel_stats: * @tx_packets (out): transmitted packets * @tx_bytes (out): transmitted bytes * @rx_packets (out): received packets * @rx_bytes (out): received bytes * * Retrieve tunnel interface traffic statistics. * * Since: 2.6.5 */ void hev_socks5_tunnel_stats (size_t *tx_packets, size_t *tx_bytes, size_t *rx_packets, size_t *rx_bytes); #ifdef __cplusplus } #endif #endif /* __HEV_MAIN_H__ */ ``` -------------------------------- ### Configure Additional Compiler Flags Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Specify extra compiler flags for cinterop processing. Example includes defining a DEBUG macro. ```kotlin compilerOpts = listOf("-DDEBUG=1") ``` -------------------------------- ### Implement Swift Async/Await Functionality Source: https://context7.com/frankois944/spm4kmp/llms.txt Demonstrates how to use Swift's async/await syntax for asynchronous operations, including error handling and completion callbacks. Ensure the minimum deployment target is set for concurrency support. ```swift // src/swift/nativeBridge/AsyncBridge.swift import Foundation @objcMembers public class AsyncBridge: NSObject { public func fetchData(completion: @escaping (String?, Error?) -> Void) { Task { do { let result = try await performAsyncWork() completion(result, nil) } catch { completion(nil, error) } } } private func performAsyncWork() async throws -> String { try await Task.sleep(nanoseconds: 1_000_000_000) return "Async result" } } ``` -------------------------------- ### Build Dummy XCFramework Source: https://github.com/frankois944/spm4kmp/blob/main/BinaryPackageSource/README.md Execute this script to build the dummy XCFramework. Ensure you update the packageVersion in build.sh to avoid caching issues. ```sh ./build.sh ``` -------------------------------- ### Configure Package Registry with Token File Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Register a Swift package registry using a token stored in a file for authentication. ```kotlin registry( url = uri("https://registry.example.com"), tokenFile = file("/path/to/token.txt"), ) ``` -------------------------------- ### Dependency Management Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Configure Swift package dependencies and product name prefixes. ```APIDOC ## Dependencies ### `dependency` block Declares one or more Swift package dependencies. Supports remote (version, branch, commit) and local (source or binary) packages. **Example:** ```kotlin dependency { remotePackageVersion( url = uri("https://github.com/firebase/firebase-ios-sdk.git"), version = "11.0.0", products = { add("FirebaseCore", exportToKotlin = true) }, ) } ``` See the full [DependencyConfig reference](dependency/dependencyConfig.md) for all available options. ### `packageDependencyPrefix` - **Type**: `String?` - **Default**: `null` (no prefix — products are imported under their own name) - **Description**: A prefix applied to all dependency product names when they are imported into Kotlin. Useful to avoid name collisions or to restore the `cocoapods.` prefix style when migrating from the CocoaPods plugin. **Example:** ```kotlin // Without prefix: import FirebaseCore.FIRApp // With prefix: import myPrefix.FirebaseCore.FIRApp packageDependencyPrefix = "myPrefix" ``` ``` -------------------------------- ### Configure Custom Swift Path and Build Settings Source: https://context7.com/frankois944/spm4kmp/llms.txt Customize Swift binary path, toolchain, and working directories for specialized build environments. This includes setting shared cache paths for CI/CD and defining a package dependency prefix. ```kotlin // build.gradle.kts kotlin { iosArm64 { swiftPackageConfig(cinteropName = "nativeBridge") { // Custom Swift binary (e.g., from swiftly) swiftBinPath = "/Users/dev/.swiftly/bin/swift" // Specific Swift toolchain toolchain = "swift-DEVELOPMENT-SNAPSHOT-2024-01-01" // Custom working directory (preserves cache on clean) spmWorkingPath = "${projectDir}/SPM" // Shared SPM cache paths for CI/CD sharedCachePath = "/shared/spm-cache" sharedConfigPath = "/shared/spm-config" sharedSecurityPath = "/shared/spm-security" // Dependency name prefix for imports packageDependencyPrefix = "myPrefix" } } } ``` -------------------------------- ### Configure Swift Package Registry Dependency Source: https://github.com/frankois944/spm4kmp/blob/main/docs/usages/packageRegistry.md Add a Swift package from a registry using the `registry` and `dependency` configurations. Ensure your server configuration and credentials are correctly set. ```kotlin iosArm64 { swiftPackageConfig { registry( url = uri("https://your/server/configuration") token = "YourCredential", ) dependency { registryPackage( id = "spm.dummy", version = "1.0.1", products = { add("registrydummy") }, ) } } } ``` -------------------------------- ### Export Swift Methods and Properties with @objcMembers Source: https://github.com/frankois944/spm4kmp/blob/main/docs/bridge.md Example of a Swift class designed for Kotlin interoperability. It must be annotated with `@objcMembers` and declared `public`. Pure Swift types are not bridgeable. ```swift import UIKit @objcMembers public class MySwiftBridge: NSObject { public func exportedMethod() -> String { return "value" } public func exportedView() -> NSObject { return UIView() } } ``` -------------------------------- ### Configure Swift Package for Apple Targets Source: https://github.com/frankois944/spm4kmp/blob/main/docs/bridge.md Minimal Gradle configuration for setting up the Swift bridge for Apple targets. Ensure `cinteropName` is set appropriately. ```kotlin kotlin { listOf( iosArm64(), iosSimulatorArm64() // and more Apple targets... ).forEach { target.swiftPackageConfig(cinteropName = "[cinteropName]") { } } } ``` -------------------------------- ### Build Configuration Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Configure build-related settings such as Swift tools version, debug mode, and binary paths. ```APIDOC ## Build Configuration ### `toolsVersion` - **Type**: `String` - **Default**: `"5.9"` - **Description**: The Swift tools version written into the `Package.swift` manifest header. This controls which SPM features and manifest APIs are available. **Example:** ```kotlin toolsVersion = "5.9" ``` ### `debug` - **Type**: `Boolean` - **Default**: `false` - **Description**: Builds the Swift package in debug configuration instead of release. Useful during development to get debug symbols, but release builds are significantly faster. **Example:** ```kotlin debug = true ``` ### `swiftBinPath` - **Type**: `String?` - **Default**: `xcrun --sdk macosx swift` - **Description**: Path to the `swift` binary used to compile the bridge. Override this to use a specific Swift version or a custom toolchain installation. **Example:** ```kotlin swiftBinPath = "/path/to/custom/swift" ``` ### `toolchain` - **Type**: `String?` - **Default**: `null` - **Description**: Swift toolchain identifier to use when building the package. See [Custom Swift Versions & Toolchains](../section-help/tips.md#support-xcode-15-and-earlier-or-another-version-of-swift) for details. **Example:** ```kotlin toolchain = "swift-DEVELOPMENT-SNAPSHOT-2024-01-01" ``` ``` -------------------------------- ### Add by ProductName Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/dependency/productPackageConfig.md Adds one or more products to the product package configuration using ProductName objects. ```APIDOC ## Add by ProductName ### Description Adds one or more products to the product package configuration. ### Method `add` ### Parameters #### Kotlin Parameters - **products** (ProductName) - Required - The products to be added. Each product is represented by a [ProductName], which includes details such as the name and an optional alias. - **exportToKotlin** (Boolean) - Optional - Determines whether the added products should be exported to Kotlin. Defaults to `false` if not specified. ### Request Example ```kotlin add( ProductName("AppMetricaCore"), exportToKotlin = true ) ``` ### Response This method does not return a value. It modifies the product package configuration in place. ``` -------------------------------- ### Swift Build Settings Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/bridgeSettingsConfig.md Configure the target's Swift build settings. ```APIDOC ## swiftSettings ### Description The target’s Swift build settings. ### Method `swiftSettings(setting: SwiftSettingConfig.() -> Unit)` ### Parameters This function takes a lambda with receiver of type `SwiftSettingConfig`. #### SwiftSettingConfig Properties - **defines** (List) - A list of Swift compiler flags to define. - **enableExperimentalFeature** (String) - Enables an experimental Swift feature. - **enableUpcomingFeature** (String) - Enables an upcoming Swift feature. - **interoperabilityMode** (String) - Sets the C++ interoperability mode. ``` -------------------------------- ### Configure Token-Based Package Registry Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Register a Swift package registry using a token for authentication. ```kotlin registry( url = uri("https://registry.example.com"), token = "my-token", ) ``` -------------------------------- ### Configure C Build Settings Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/bridgeSettingsConfig.md Configures the C build settings for a target. Use this to specify C defines, header search paths, and unsafe flags. ```kotlin public fun cSetting(setting: CSettingConfig.() -> Unit) ``` -------------------------------- ### C Build Settings Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/bridgeSettingsConfig.md Configure the target's C build settings. ```APIDOC ## cSetting ### Description The target’s C build settings. ### Method `cSetting(setting: CSettingConfig.() -> Unit)` ### Parameters This function takes a lambda with receiver of type `CSettingConfig`. #### CSettingConfig Properties - **defines** (List>) - A list of preprocessor macros to define. - **headerSearchPath** (List) - A list of paths to search for header files. - **unsafeFlags** (List) - A list of unsafe C compiler flags. ``` -------------------------------- ### Add Products by String Name Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/dependency/productPackageConfig.md Add one or more products to the configuration using their string representations. The `exportToKotlin` parameter determines if the products are exported to Kotlin. ```Kotlin fun add( vararg names: String, exportToKotlin: Boolean = false, ) ``` -------------------------------- ### Configure Username & Password Package Registry Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Register a Swift package registry requiring username and password authentication. ```kotlin registry( url = uri("https://registry.example.com"), username = "user", password = "secret", ) ``` -------------------------------- ### Configure Swift Package Manager for Targets Source: https://github.com/frankois944/spm4kmp/blob/main/README.md Configure the Swift Package Manager for your Apple targets in build.gradle.kts. The `cinteropName` is recommended for clarity and compatibility. ```kotlin kotlin { listOf( iosArm64(), iosSimulatorArm64() // and more Apple targets... ).forEach { target -> // `cinteropName` is recommended when using a list of native target // Or when you want to keep the compatibility with the legacy way (cf: [cinteropName]) // If not set, It will take the name of the current Target target.swiftPackageConfig(cinteropName = "[cinteropName]") { // create a new directory at `src/swift/[cinteropName]` } } } ``` -------------------------------- ### Configure Multi-Target Swift Packages Source: https://context7.com/frankois944/spm4kmp/llms.txt Configure different Swift packages for different Apple platforms with separate bridge folders and target-specific settings like minimum OS versions. ```kotlin // build.gradle.kts kotlin { // iOS configuration listOf(iosArm64(), iosSimulatorArm64()).forEach { target -> target.swiftPackageConfig(cinteropName = "nativeIosShared") { minIos = "16.0" dependency { remotePackageVersion( url = uri("https://github.com/firebase/firebase-ios-sdk"), version = "11.8.0", products = { add("FirebaseAnalytics", exportToKotlin = true) }, ) } } } // macOS configuration macosArm64 { swiftPackageConfig { minMacos = "12.0" dependency { remotePackageVersion( url = uri("https://github.com/krzyzanowskim/CryptoSwift.git"), version = "1.8.4", products = { add("CryptoSwift") }, ) } } } } ``` -------------------------------- ### Android KmpPlayer Implementation Source: https://github.com/frankois944/spm4kmp/blob/main/docs/usages/distribution.md Implements the KmpPlayer for Android using ExoPlayer. Initializes the player, sets the media item, and manages its lifecycle within a DisposableEffect. Uses AndroidView to embed the PlayerView. ```kotlin @Composable public actual fun KmpPlayer(modifier: Modifier, url: String) { val context = LocalContext.current // Initialize ExoPlayer val exoPlayer = ExoPlayer.Builder(context).build() val mediaSource = remember(url) { MediaItem.fromUri(url) } LaunchedEffect(url) { exoPlayer.setMediaItem(mediaSource) exoPlayer.prepare() } // Manage lifecycle events DisposableEffect(Unit) { onDispose { exoPlayer.release() } } AndroidView( factory = { ctx -> PlayerView(ctx).apply { player = exoPlayer } }, modifier = modifier ) } ``` -------------------------------- ### CSettingConfig - defines Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/targetSettingsConfigs/CSettingConfig.md Defines a value for a macro. ```APIDOC ## CSettingConfig - defines ### Description Defines a value for a macro. ### Property - **defines** (List>) - Description: A list of key-value pairs representing macro definitions. ``` -------------------------------- ### Source Paths Configuration Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Configure the source paths for Swift bridge files and the working directory for SPM files. ```APIDOC ## Source Paths ### `customPackageSourcePath` Configures the directory containing your Swift bridge source files. The plugin copies these files to the build directory and compiles them. - **Type**: `String` - **Default**: `src/swift/[cinteropName]` (or `src/swift/[targetName]` if `cinteropName` is not set) **Example:** ```kotlin swiftPackageConfig(cinteropName = "nativeBridge") { customPackageSourcePath = "src/custom/swift" } ``` ### `spmWorkingPath` Specifies the build directory where the plugin generates SPM files, including `Package.swift` and resolved dependencies. - **Type**: `String` - **Default**: `{buildDir}/spmKmpPlugin/` **Example:** ```kotlin var spmWorkingPath: String ``` ``` -------------------------------- ### Linker Settings Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/bridgeSettingsConfig.md Configure the target's linker settings. ```APIDOC ## linkerSetting ### Description The target’s linker settings. ### Method `linkerSetting(setting: LinkerSettingConfig.() -> Unit)` ### Parameters This function takes a lambda with receiver of type `LinkerSettingConfig`. #### LinkerSettingConfig Properties - **linkedFramework** (List) - A list of frameworks to link against. - **linkedLibrary** (List) - A list of libraries to link against. - **unsafeFlags** (List) - A list of unsafe linker flags. ``` -------------------------------- ### Configure Swift Package Registries Source: https://context7.com/frankois944/spm4kmp/llms.txt Set up Swift package registries for Git-alternative sources, including support for unauthenticated, token-authenticated, and username/password-authenticated registries. Define package dependencies from registries. ```kotlin // build.gradle.kts kotlin { iosArm64 { swiftPackageConfig(cinteropName = "nativeBridge") { // Unauthenticated registry registry(url = uri("https://registry.example.com")) // Registry with token authentication registry( url = uri("https://private-registry.example.com"), token = "my-auth-token", ) // Registry with username/password registry( url = uri("https://private-registry.example.com"), username = "user", password = "secret", ) dependency { registryPackage( id = "com.example.mypackage", version = "1.0.1", products = { add("MyPackage") }, ) } } } } ``` -------------------------------- ### Legacy Configuration: Create Cinterops Source: https://github.com/frankois944/spm4kmp/blob/main/docs/setup.md In legacy configurations (pre-1.1.0), create cinterops for multiple targets within the `compilations` block in `build.gradle.kts`. Ensure the cinterop name matches when creating the `swiftPackageConfig`. ```kotlin kotlin { listOf( iosArm64(), iosSimulatorArm64() // and more Apple targets... ).forEach { it.compilations { val main by getting { cinterops.create("[cinteropName]") } } } } ``` ```kotlin swiftPackageConfig { create("[cinteropName]") { // must match cinterops.create name } } ``` -------------------------------- ### Usage of Native UIKit Views in Kotlin Source: https://context7.com/frankois944/spm4kmp/llms.txt Demonstrates how to use native UIKit views and view controllers created in Swift from Kotlin code. This includes direct usage of UIView and casting from NSObject. ```kotlin // iosMain/kotlin/com/example/UIKitUsage.kt import nativeBridge.UIKitBridge import platform.UIKit.UIView import platform.UIKit.UIViewController fun createNativeViews() { val bridge = UIKitBridge() // Direct UIView val view: UIView = bridge.createView() // Casting from NSObject val viewCasted: UIView = bridge.createViewAsNSObject() as UIView // UIViewController val viewController: UIViewController = bridge.createViewController() } ``` -------------------------------- ### Add by Names Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/dependency/productPackageConfig.md Adds one or more product names to the product package configuration using their string representations. ```APIDOC ## Add by Names ### Description Adds one or more product names to the product package configuration using their string representation. ### Method `add` ### Parameters #### Kotlin Parameters - **names** (String) - Required - The string representations of the product names to be added. Each string corresponds to the name of the product within the Swift package ecosystem. - **exportToKotlin** (Boolean) - Optional - Determines whether the added products should be exported to Kotlin. Defaults to `false` if not specified. ### Request Example ```kotlin add( "AppMetricaCore", "AppMetricaRemoteConfig", exportToKotlin = true ) ``` ### Response This method does not return a value. It modifies the product package configuration in place. ``` -------------------------------- ### Deployment Targets Configuration Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Set minimum deployment targets for various Apple platforms. ```APIDOC ## Deployment Targets Setting a platform to `null` removes it from the generated `Package.swift` manifest. ### `minIos` - **Type**: `String?` - **Default**: `"12.0"` - **Description**: Minimum iOS deployment target. **Example:** ```kotlin minIos = "16.0" ``` ### `minMacos` - **Type**: `String?` - **Default**: `"10.13"` - **Description**: Minimum macOS deployment target. **Example:** ```kotlin minMacos = "12.0" ``` ### `minTvos` - **Type**: `String?` - **Default**: `"12.0"` - **Description**: Minimum tvOS deployment target. **Example:** ```kotlin minTvos = "16.0" ``` ### `minWatchos` - **Type**: `String?` - **Default**: `"4.0"` - **Description**: Minimum watchOS deployment target. **Example:** ```kotlin minWatchos = "7.0" ``` ``` -------------------------------- ### Enable Swift Concurrency in iOS Tests Source: https://context7.com/frankois944/spm4kmp/llms.txt Configure minimum deployment targets for iOS tests when using Swift async/await to avoid concurrency library loading errors. This involves setting the minimum OS version and overriding Konan properties. ```kotlin // build.gradle.kts kotlin { iosSimulatorArm64 { swiftPackageConfig(cinteropName = "nativeBridge") { minIos = "16.0" } // Fix for "Library not loaded: libswift_Concurrency.dylib" in tests binaries.getTest("debug").apply { freeCompilerArgs += listOf( "-Xoverride-konan-properties=osVersionMin.ios_simulator_arm64=16.0", ) } } } ``` -------------------------------- ### Configure Swift Build Settings Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/bridgeSettingsConfig.md Configures the Swift build settings for a target. Use this to specify Swift defines, experimental features, upcoming features, and interoperability modes. ```kotlin public fun swiftSettings(setting: SwiftSettingConfig.() -> Unit) ``` -------------------------------- ### Add Products by ProductName Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/dependency/productPackageConfig.md Add one or more products to the configuration using ProductName objects. The `exportToKotlin` parameter determines if the products are exported to Kotlin. ```Kotlin fun add( vararg products: ProductName, exportToKotlin: Boolean = false, ) ``` -------------------------------- ### CSettingConfig - headerSearchPath Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/targetSettingsConfigs/CSettingConfig.md Provides a header search path relative to the target’s directory. ```APIDOC ## CSettingConfig - headerSearchPath ### Description Provides a header search path relative to the target’s directory. ### Property - **headerSearchPath** (List) - Description: A list of strings representing header search paths. ``` -------------------------------- ### C++ Build Settings Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/bridgeSettingsConfig.md Configure the target's C++ build settings. ```APIDOC ## cxxSetting ### Description The target’s C++ build settings. ### Method `cxxSetting(setting: CxxSettingConfig.() -> Unit)` ### Parameters This function takes a lambda with receiver of type `CxxSettingConfig`. #### CxxSettingConfig Properties - **defines** (List>) - A list of preprocessor macros to define. - **headerSearchPath** (List) - A list of paths to search for header files. - **unsafeFlags** (List) - A list of unsafe C++ compiler flags. ``` -------------------------------- ### Set Minimum macOS Deployment Target Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Configures the minimum macOS version for the generated Package.swift manifest. ```kotlin minMacos = "12.0" ``` -------------------------------- ### Configure Single Target Swift Package Configuration Source: https://github.com/frankois944/spm4kmp/blob/main/docs/setup.md Configure a single target's Swift package configuration in `build.gradle.kts`. `cinteropName` is optional and defaults to the target name. This creates configuration files in `src/swift/[targetName]/`. ```kotlin kotlin { iosArm64 { swiftPackageConfig { // creates src/swift/iosArm64/ } } } ``` -------------------------------- ### Configure Linker Settings Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/bridgeSettingsConfig.md Configures the linker settings for a target. Use this to specify linked frameworks, libraries, and unsafe flags. ```kotlin public fun linkerSetting(setting: LinkerSettingConfig.() -> Unit) ``` -------------------------------- ### Configure Swift Bridge Settings Source: https://context7.com/frankois944/spm4kmp/llms.txt Set C, C++, and Swift compiler flags, defines, and linker options for the Swift bridge. Ensure correct header search paths and unsafe flags are specified. ```kotlin // build.gradle.kts kotlin { iosArm64 { swiftPackageConfig(cinteropName = "nativeBridge") { bridgeSettings { cSetting { defines = listOf(Pair("C_DEBUG", "1")) headerSearchPath = listOf("./includes/") unsafeFlags = listOf("-W") } cxxSetting { defines = listOf(Pair("CXX_DEBUG", "1")) headerSearchPath = listOf("./includes/") } swiftSettings { defines = listOf("CUSTOM_DEFINE") enableExperimentalFeature = "StrictConcurrency" enableUpcomingFeature = "ExistentialAny" interoperabilityMode = "Cxx" } linkerSetting { linkedFramework = listOf("UIKit", "CoreData") linkedLibrary = listOf("sqlite3") unsafeFlags = listOf("-lz") } } } } } ``` -------------------------------- ### Configure C++ Build Settings Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/bridgeSettingsConfig.md Configures the C++ build settings for a target. Use this to specify C++ defines, header search paths, and unsafe flags. ```kotlin public fun cxxSetting(setting: CxxSettingConfig.() -> Unit) ``` -------------------------------- ### Legacy Swift Package Configuration for iOS and macOS Source: https://github.com/frankois944/spm4kmp/blob/main/docs/usages/multiTarget.md Legacy configuration for Swift Package Manager, creating configurations for both iOS ('nativeIosShared') and macOS ('nativeMacosShared') targets. This method is for versions prior to 1.1.0. ```kotlin listOf( iosX64(), iosSimulatorArm64(), ).forEach { it.compilations { val main by getting { cinterops.create("nativeIosShared") // a config for iOS } } } listOf( macosArm64(), ).forEach { it.compilations { val main by getting { cinterops.create("nativeMacosShared") // a config for macos } } } swiftPackageConfig { create("nativeIosShared") { // your embedded swift is inside the folder src/swift/nativeIosShared // your config for iOS } create("nativeMacosShared") { // your embedded swift is inside the folder src/swift/nativeMacosShared // your config for macOS } } ``` -------------------------------- ### Specify Header Search Paths Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/targetSettingsConfigs/CSettingConfig.md Provides a list of header search paths relative to the target's directory. ```kotlin var headerSearchPath: List ``` -------------------------------- ### Configure Swift Binary Path in spm Configuration Source: https://github.com/frankois944/spm4kmp/blob/main/docs/section-help/tips.md Specify a custom path to the Swift binary, useful for managing multiple Swift versions or older Xcode toolchains. This uses the `swiftBinPath` property. ```kotlin spm { // ... swiftBinPath = "/path/to/.swiftly/bin/swift" } ``` -------------------------------- ### Enable Debug Builds Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Builds the Swift package in debug configuration instead of release. Useful for development with debug symbols. ```kotlin debug = true ``` -------------------------------- ### Configure Multiple Targets with cinteropName Source: https://github.com/frankois944/spm4kmp/blob/main/docs/setup.md Configure multiple targets in `build.gradle.kts` using `cinteropName` for a shared bridge, recommended for compatibility with legacy configurations. This creates Swift package configuration files in `src/swift/[cinteropName]/`. ```kotlin kotlin { listOf( iosArm64(), iosSimulatorArm64() // and more Apple targets... ).forEach { target -> target.swiftPackageConfig(cinteropName = "[cinteropName]") { // creates src/swift/[cinteropName]/ } } } ``` -------------------------------- ### Configure Module build.gradle.kts for SPM Dependencies Source: https://github.com/frankois944/spm4kmp/blob/main/docs/migration/migrateFromCocoapods.md Replace the cocoapods block with swiftPackageConfig for iOS targets, defining remote Swift Package Manager dependencies. ```kotlin plugins { alias(libs.plugins.kotlinMultiplatform) -- alias(libs.plugins.kotlinCocoapods) ++ alias(libs.plugins.spmForKmp) } group = "org.jetbrains.kotlin.shared" version = "1.0-SNAPSHOT" kotlin { - iosArm64() - iosSimulatorArm64() - cocoapods { - summary = "Kotlin module with cocoapods dependencies" - ios.deploymentTarget = "16.6" - pod("FirebaseCore") { - version = libs.versions.firebaseIOS.get() - } - pod("FirebaseAnalytics") { - version = libs.versions.firebaseIOS.get() - } - pod("CryptoSwift") { - version = "1.2.3" - linkOnly = true - } - } + listOf( + iosArm64(), + iosSimulatorArm64() + ).forEach { + it.swiftPackageConfig(cinteropName = "nativeBridge") { + minIos = "16.6" + dependency { + remotePackageVersion( + url = uri("https://github.com/firebase/firebase-ios-sdk.git"), + products = { + add("FirebaseCore", "FirebaseAnalytics", exportToKotlin = true) + }, + version = libs.versions.firebaseIOS.get(), + ) + remotePackageVersion( + url = uri("https://github.com/krzyzanowskim/CryptoSwift"), + products = { + add("CryptoSwift") + }, + version = "1.2.3", + ) + } + } + } } ``` -------------------------------- ### Specify Local Binary Dependency Source: https://github.com/frankois944/spm4kmp/blob/main/docs/bridgeWithDependencies.md Declare a dependency on a local binary framework (XCFramework). The path should point to the .xcframework bundle. ```kotlin localBinary( path = "/path/to/LocalFramework.xcframework", packageName = "LocalFramework", ) ``` -------------------------------- ### Set Minimum watchOS Deployment Target Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Configures the minimum watchOS version for the generated Package.swift manifest. ```kotlin minWatchos = "7.0" ``` -------------------------------- ### Gradle Plugin Configuration for Local Package Source: https://github.com/frankois944/spm4kmp/blob/main/docs/usages/largebridge.md Configures the Kotlin Multiplatform project to include a local Swift package. Specify the absolute path to your local package and its products to be exported to Kotlin. ```kotlin kotlin { iosArm64 { swiftPackageConfig { localPackage( // absolute path to your Local Package path = "$projectDir/../MyStripeSDK", packageName = "MyStripeSDK", products = { // Export to Kotlin for use in shared Kotlin code, false by default add("MyStripeSDK", exportToKotlin = true) } ) } } } ``` -------------------------------- ### Apply Gradle Plugin Source: https://github.com/frankois944/spm4kmp/blob/main/README.md Apply the spmForKmp plugin in your build.gradle.kts file. Replace '[version]' with the actual plugin version. ```kotlin plugins { id("org.jetbrains.kotlin.multiplatform") id("io.github.frankois944.spmForKmp") version "[version]" } ``` -------------------------------- ### Set Minimum tvOS Deployment Target Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Configures the minimum tvOS version for the generated Package.swift manifest. ```kotlin minTvos = "16.0" ``` -------------------------------- ### Enable Kotlin MPP Interop Source: https://github.com/frankois944/spm4kmp/blob/main/README.md Ensure Kotlin C-interop commonization is enabled in your gradle.properties file. ```properties kotlin.mpp.enableCInteropCommonization=true ``` -------------------------------- ### Set Minimum iOS Deployment Target Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Configures the minimum iOS version for the generated Package.swift manifest. ```kotlin minIos = "16.0" ``` -------------------------------- ### Configure Swift Package Settings per Apple Target Source: https://context7.com/frankois944/spm4kmp/llms.txt Configure Swift package settings for each Apple target using `swiftPackageConfig`. This action creates a bridge folder at `src/swift/[cinteropName]` for your Swift files and specifies minimum OS versions, tools version, and build type. ```kotlin kotlin { listOf( iosArm64(), iosSimulatorArm64() ).forEach { target.swiftPackageConfig(cinteropName = "nativeBridge") { minIos = "16.0" minMacos = "12.0" minTvos = "16.0" minWatchos = "7.0" toolsVersion = "5.9" debug = false // Release build for faster compilation } } } ``` -------------------------------- ### Add Remote Swift Package by Commit Hash Source: https://context7.com/frankois944/spm4kmp/llms.txt Pin to a specific commit hash for reproducible builds and precise dependency control. Ensure the URL points to a valid Git repository. ```kotlin // build.gradle.kts kotlin { iosArm64 { swiftPackageConfig(cinteropName = "nativeBridge") { dependency { remotePackageCommit( url = uri("https://github.com/krzyzanowskim/CryptoSwift.git"), revision = "729e01bc9b9dab466ac85f21fb9ee2bc1c61b258", products = { add("CryptoSwift") }, ) } } } } ``` -------------------------------- ### Add Remote Binary Dependencies Source: https://context7.com/frankois944/spm4kmp/llms.txt Reference remote XCFramework binaries hosted on a server with checksum verification. Ensure the URL is accessible and the checksum is accurate. ```kotlin // build.gradle.kts kotlin { iosArm64 { swiftPackageConfig(cinteropName = "nativeBridge") { dependency { remoteBinary( url = uri("https://example.com/RemoteFramework.xcframework.zip"), packageName = "RemoteFramework", checksum = "abc123def456...", exportToKotlin = true, ) } } } } ``` -------------------------------- ### Enable Experimental Swift Feature Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/targetSettingsConfigs/SwiftSettingConfig.md Use 'enableExperimentalFeature' to enable a specific experimental feature by its name. This property is optional. ```kotlin var enableExperimentalFeature: String? ``` -------------------------------- ### Inspect Generated Module Maps Source: https://github.com/frankois944/spm4kmp/blob/main/docs/section-help/faq.md Use these commands to inspect the generated Objective-C header and module maps for Swift packages. This helps verify if a package has an Objective-C compatible interface. ```bash # Framework-based products [project]/build/spmKmpPlugin/[cinteropName]/scratch/release/[product].framework/Modules/module.modulemap # Static library products [project]/build/spmKmpPlugin/[cinteropName]/scratch/release/[product].build/module.modulemap ``` -------------------------------- ### Add Local Swift Package Dependency Source: https://context7.com/frankois944/spm4kmp/llms.txt Reference a local Swift package from your filesystem for development or proprietary packages. Use an absolute path for clarity. ```kotlin // build.gradle.kts kotlin { iosArm64 { swiftPackageConfig(cinteropName = "nativeBridge") { dependency { localPackage( path = "/absolute/path/to/MyLocalPackage", packageName = "MyLocalPackage", products = { add("MyLocalPackage") }, ) } } } } ``` -------------------------------- ### Update Xcode Build Settings for Framework Search Paths Source: https://github.com/frankois944/spm4kmp/blob/main/docs/migration/migrateFromCocoapods.md Configure 'Other Linker Flags' and 'Framework Search Paths' in Xcode's Build Settings to include the shared framework. ```text Setting | Value | --- | --- | | **Other Linker Flags** | -framework shared | | **Framework Search Paths** | $(SRCROOT)/../build/xcode-frameworks/$(CONFIGURATION)/$(SDK_NAME) ``` -------------------------------- ### Set Package Dependency Prefix Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Applies a prefix to all dependency product names when imported into Kotlin, useful for avoiding name collisions. ```kotlin packageDependencyPrefix = "myPrefix" ``` -------------------------------- ### Gradle Configuration for HevSocks5Tunnel Source: https://github.com/frankois944/spm4kmp/blob/main/docs/usages/importCLangFramework.md This Gradle Kotlin script configures the remote binary import for HevSocks5Tunnel. Ensure 'isCLang' is set to true for C-language based xcFrameworks. The checksum is crucial for integrity. ```kotlin remoteBinary( url = uri("https://github.com/wanliyunyan/HevSocks5Tunnel/releases/download/2.10.0/HevSocks5Tunnel.xcframework.zip"), packageName = "HevSocks5Tunnel", exportToKotlin = true, checksum = "f66fc314edbdb7611c5e8522bc50ee62e7930f37f80631b8d08b2a40c81a631a", isCLang = true, // Required ) ``` -------------------------------- ### Configure SwiftPackageConfig for iOS Targets Source: https://github.com/frankois944/spm4kmp/blob/main/docs/references/swiftPackageConfig.md Applies SwiftPackageConfig settings, including cinterop name and minimum iOS version, to specified iOS targets. ```kotlin kotlin { listOf(iosArm64(), iosSimulatorArm64()).forEach { target -> target.swiftPackageConfig(cinteropName = "nativeBridge") { minIos = "16.0" debug = false dependency { ... } } } } ```