> For the complete documentation index, see [llms.txt](https://docs.nubrick.app/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.nubrick.app/reference/ios/nubricksdk.md).

# NubrickSDK

`NubrickSDK` は iOS SDK のエントリポイントです。初期化、イベント送信、埋め込み、Remote Config、ユーザープロパティ更新を静的メソッドで扱います。

{% hint style="warning" %}
`NubrickSDK.initialize(...)` は、アプリ起動時に 1 回だけ実行してください。\
`embedding` / `overlay` / `remoteConfig` / `dispatch` などの API は、初期化完了後に利用してください。\
SwiftUI では、`@main` の `App` struct の `init()` で初期化する構成を推奨します。
{% endhint %}

### 定義 <a href="#definition" id="definition"></a>

```swift
public enum NubrickSDK {
    @MainActor
    public static func initialize(
        projectId: String,
        onEvent: (@Sendable (_ event: ComponentEvent) -> Void)? = nil,
        httpRequestInterceptor: NubrickHttpRequestInterceptor? = nil,
        onDispatch: ((_ event: NubrickEvent) -> Void)? = nil,
        trackCrashes: Bool = true
    )

    public nonisolated static func dispatch(_ event: NubrickEvent)

    @MainActor public static func overlayViewController() -> UIViewController
    @MainActor public static func overlay() -> some View

    @MainActor
    public static func embedding(
        _ id: String,
        arguments: NubrickArguments? = nil,
        onEvent: ((_ event: ComponentEvent) -> Void)? = nil,
        onSizeChange: ((_ width: NubrickSize, _ height: NubrickSize) -> Void)? = nil
    ) -> some View

    @MainActor
    public static func embedding<V: View>(
        _ id: String,
        arguments: NubrickArguments? = nil,
        onEvent: ((_ event: ComponentEvent) -> Void)? = nil,
        @ViewBuilder content: @escaping (_ phase: SwiftUIEmbeddingPhase) -> V,
        onSizeChange: ((_ width: NubrickSize, _ height: NubrickSize) -> Void)? = nil
    ) -> some View

    @MainActor
    public static func embeddingUIView(
        _ id: String,
        arguments: NubrickArguments? = nil,
        onEvent: ((_ event: ComponentEvent) -> Void)? = nil,
        onSizeChange: ((_ width: NubrickSize, _ height: NubrickSize) -> Void)? = nil
    ) -> UIView

    @MainActor
    public static func embeddingUIView(
        _ id: String,
        arguments: NubrickArguments? = nil,
        onEvent: ((_ event: ComponentEvent) -> Void)? = nil,
        content: @escaping (_ phase: UIKitEmbeddingPhase) -> UIView,
        onSizeChange: ((_ width: NubrickSize, _ height: NubrickSize) -> Void)? = nil
    ) -> UIView

    public static func remoteConfig(
        _ id: String,
        phase: @escaping (@Sendable (_ phase: RemoteConfigPhase) -> Void)
    )

    @MainActor
    public static func remoteConfigAsView<V: View>(
        _ id: String,
        @ViewBuilder phase: @escaping ((_ phase: RemoteConfigPhase) -> V)
    ) -> some View

    @MainActor public static func setUserProperties(_ properties: [String: Any])
    @MainActor public static func setUserProperty(_ key: String, value: Any)
    @MainActor public static func setUserId(_ id: String)
    @MainActor public static func getUserProperty(_ key: String) -> String?
    @MainActor public static func getUserId() -> String?
    @MainActor public static func getUserProperties() -> [String: String]
}

public typealias NubrickArguments = [String: any Sendable]
public typealias NubrickHttpRequestInterceptor = @Sendable (_ request: URLRequest) -> URLRequest

@frozen
public enum NubrickSize: Sendable {
    case fixed(CGFloat)
    case fill
}
```

### 初期化 <a href="#init" id="init"></a>

```swift
import Nubrick

@main
@MainActor
struct YourApp: App {
    init() {
        NubrickSDK.initialize(projectId: "<YOUR_PROJECT_ID>")
    }

    var body: some Scene {
        WindowGroup {
            NubrickProvider {
                ContentView()
            }
        }
    }
}
```

### イベント送信 <a href="#events" id="events"></a>

```swift
NubrickSDK.dispatch(NubrickEvent("PURCHASE_COMPLETED"))
```

購入金額などをイベントに付ける方法は、[イベントプロパティ](https://docs.nubrick.app/reference/ios/events.md#properties)を参照してください。

### 埋め込み（SwiftUI） <a href="#swiftui" id="swiftui"></a>

```swift
NubrickSDK.embedding("TOP_COMPONENT")
    .frame(height: 240)
```

フェーズを使う場合:

```swift
NubrickSDK.embedding("TOP_COMPONENT") { phase in
    switch phase {
    case .loading:
        ProgressView()
    case .notFound:
        Text("not found")
    case .failed:
        Text("error")
    case .completed(let view):
        view.frame(height: 240)
    }
}
```

### 埋め込み（UIKit） <a href="#uikit" id="uikit"></a>

```swift
let view = NubrickSDK.embeddingUIView("TOP_COMPONENT")
self.view.addSubview(view)
```

### 埋め込みサイズの取得 <a href="#size" id="size"></a>

`onSizeChange` を使うと、埋め込みコンポーネントの実サイズを取得できます。\
このコールバックは、実際の埋め込みページが読み込まれたときだけ呼ばれます。`loading` / `notFound` / `failed` では呼ばれません。

```swift
NubrickSDK.embedding(
    "TOP_COMPONENT",
    onSizeChange: { width, height in
        print(width, height)
    }
)
```

`NubrickSize` の意味:

* `.fixed(value)` は、エディタで固定サイズが設定されていることを表します。
* `.fill` は、その軸に固定サイズがなく、ホスト側のレイアウトに従うことを表します。

### Remote Config

```swift
NubrickSDK.remoteConfig("FEATURE_FLAGS") { phase in
    switch phase {
    case .completed(let variant):
        print(variant.getAsBool("new_checkout") ?? false)
    default:
        break
    }
}
```

### ユーザープロパティ <a href="#properties" id="properties"></a>

{% hint style="warning" %}
この値は、施策のデータを識別するためにNubrickサーバーに送信されます。そのため、氏名やメールアドレスなどの個人情報は、user\_id として使用しないでください。\
詳細はこちらのドキュメントもご覧ください。

[ユーザー属性情報（setProperties）について](https://docs.nubrick.app/other/setproperties.md)
{% endhint %}

{% hint style="info" %}
このプロパティは、

* どのユーザーが施策のターゲットとなるかをフィルタリングする
* 施策内のユーザー毎の動的な変数として表示する

ために使用されます。
{% endhint %}

```swift
NubrickSDK.setUserProperties([
    "plan": "gold",
    "isPremium": true,
    "age": 32
])

NubrickSDK.setUserId("<CUSTOM_USER_ID>")

let userId = NubrickSDK.getUserId()
let props = NubrickSDK.getUserProperties()
```

### ビルトインのユーザープロパティ <a href="#builtin" id="builtin"></a>

デフォルトで、以下のビルトインプロパティが設定されています：

| Key               | Description                                                              |
| ----------------- | ------------------------------------------------------------------------ |
| `userId`          | User id (uuid by default)                                                |
| `languageCode`    | language code (e.g. en for English, fr for French)                       |
| `regionCode`      | region code (e.g. US for United States, GB for United Kingdom)           |
| `sdkVersion`      | nubrick sdk version                                                      |
| `osName`          | os name (e.g. iOS, iPadOS)                                               |
| `osVersion`       | os version (e.g. 15.3.2)                                                 |
| `appId`           | your app bundle identifier                                               |
| `appVersion`      | your app version (e.g. `CFBundleShortVersionString` for Apple platforms) |
| `cfBundleVersion` | your apple app `CFBundleVersion`                                         |

### 補足 <a href="#notes" id="notes"></a>

* `setUserProperties` / `setUserProperty` の値は `String`, `Bool`, `Int`, `Double`, `Date` などを渡せます。
* プロパティのキーは半角英数字と `_` `-` のみ利用できます。camelCase（`isPremium` など）を推奨します。詳細は [ユーザー属性情報（setProperties）について](https://docs.nubrick.app/other/setproperties.md) を参照してください。
* `getUserProperties()` は、アプリが設定したカスタム値と `userId` を取得できます。
* 失敗系の状態は [Phases](https://docs.nubrick.app/reference/ios/phases.md) を参照してください。
