# NubrickSDK

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

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

### 定義

```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
}
```

### 初期化

```swift
import Nubrick

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

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

### イベント送信

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

### 埋め込み（SwiftUI）

```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）

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

### 埋め込みサイズの取得

`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
    }
}
```

### ユーザープロパティ

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

[ユーザー属性情報（setProperties）について](/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()
```

### ビルトインのユーザープロパティ

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

| 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`                                         |

### 補足

* `setUserProperties` / `setUserProperty` の値は `String`, `Bool`, `Int`, `Double`, `Date` などを渡せます。
* `getUserProperties()` は、アプリが設定したカスタム値と `userId` を取得できます。
* 失敗系の状態は [Phases](/reference/ios/phases.md) を参照してください。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.nubrick.app/reference/ios/nubricksdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
