# iOS SDK

Roboflow Mobile iOS SDK は、高速な推論のために、または新しい一連の機能・性能・ユースケース（拡張現実など）を実現するために、edge（iPad または iPhone）上でモデルを実行する必要がある iOS アプリケーションを開発している場合に最適な選択肢です。

カスタムのコンピュータビジョンモデルを組み込んだネイティブモバイルアプリケーションにより、開発者はアプリに視覚を与えることができます。

## サポートされるタスク

以下のタスクタイプが hosted API でサポートされています:

| タスクタイプ           | iOS SDK Deployment でサポート |
| ---------------- | ------------------------ |
| 物体検出             | ✅                        |
| 分類               |                          |
| インスタンスセグメンテーション  | ✅（iOS 18 以上）             |
| セマンティックセグメンテーション |                          |

### CoreML Export 互換性

以下のモデルアーキテクチャは、オンデバイス deployment 用の CoreML（`.mlpackage`）export をサポートしています:

| モデル      | CoreML Export |
| -------- | ------------- |
| RF-DETR  | ✅             |
| YoloLite | ✅             |
| 分類モデル    | ✅             |

## モデルを iOS デバイスに Deploy する

### サポートされるハードウェアとソフトウェア

すべての iOS デバイスはオンデバイス推論をサポートしていますが、iPhone 8（A11 Bionic Processor）より古いものは、エネルギー効率の低い gpu engine にフォールバックします。

Roboflow では、最小 iOS バージョン 15.4（インスタンスセグメンテーションモデルでは 18.0）が必要です。

## プロトタイピング

以下を使って開発できます [Roboflow Serverless Hosted API](https://docs.roboflow.com/deploy/serverless)。これはオンデバイス推論と同じ学習済みモデルを使用します。

## インストール

* インストール [CocoaPods](https://guides.cocoapods.org/using/getting-started.html) | [トラブルシューティングガイド](https://guides.cocoapods.org/using/troubleshooting#installing-cocoapods)

「CocoaPods は Ruby で構築されており、macOS に標準で用意されている Ruby でインストールできます。Ruby Version manager を使用することもできますが、何をしているかを理解している場合を除き、macOS に標準搭載されている Ruby を使用することを推奨します。デフォルトの Ruby を使用してインストールする場合、gems のインストール時に `sudo` を使用する必要があります。（ただし、これは gem のインストール中のみの問題です。）」 - [CocoaPods](https://guides.cocoapods.org/using/getting-started.html)

このプロセスで RubyGems に管理者権限を与えたくない場合は、「Sudo-less」インストールも選択肢です。ただし、 `sudo` インストールのほうがより一般的である点に注意してください。

次を入力して、CocoaPods が正常にインストールされたことを確認してください `pod --version` を Terminal で実行します。

### Roboflow CocoaPod のインストール

まず、次を実行します `pod init` をプロジェクトディレクトリで実行します。

以下を確認してください `Podfile` に次が指定されていることを確認してください `platform :ios, '15.4'`

次に、以下を追加します `pod 'Roboflow'` をあなたの `Podfile`.

XCode Command Line Tools がインストールされていない場合は、次を実行します `xcode-select --install` を Terminal で実行します。

これにより次が返されます: `xcode-select: error: command line tools are alreadyinstalled, use "Software Update" to install updates` Command Line Tools がすでにシステムに存在する場合。

最後に、次を実行します `pod install` を実行し、生成された `.xcworkspace` ファイルを次で開きます [XCode](https://developer.apple.com/xcode/).

![Podfile のインストールが成功した後の Terminal](/files/64434150043020401a8a6b8acf7a365391cb367e)

![Podfile のインストールが成功した後のプロジェクトディレクトリ](/files/2da66994d2a7ffc71b12b5f5c9d9f4c1888bcb6e)

* 次のエラーが返される場合: 「You may have encountered a bug in the Ruby interpreter or extension libraries,」 その場合はまず次を実行してください `brew install cocoapods`、その後に次を実行します `pod install` を実行し、生成された `.xcworkspace` ファイルを XCode で開きます。
  * 次を入力して、CocoaPods が正常にインストールされたことを確認してください `pod --version` を Terminal で実行します。

### Swift で Roboflow を使用する

次へ移動します `.xcworkspace` ファイルを XCode で開きます。

![](/files/2295650ae62d8e5dc623df8b7a1b2679dd1b7fdd)

次に、以下を追加して Roboflow を import します `import Roboflow`。を `.xcworkspace` ファイルに追加します。

次に、以下を使って Roboflow API のインスタンスを作成します `let rf = Roboflow(apiKey: "API_KEY")`。 `modelVersion`については、 `YOUR-MODEL-VERSION-#` をモデルのバージョン番号の整数値に置き換えてください。

#### Project 情報の確認

**Completion Handler の使い方:**

```swift
import Roboflow
...
//API Key で初期化
let rf = RoboflowMobile(apiKey: "API_KEY")
var model: RFModel?
...

//model はあなたのモデルの project 名です
rf.load(model: "YOUR-MODEL-ID", modelVersion: YOUR-MODEL-VERSION-#) { [self] model, error, modelName, modelType in
    if error != nil {
        print(error?.localizedDescription as Any)
    } else {
        model?.configure(threshold: threshold, overlap: overlap, maxObjects: maxObjects
                            processingMode: .performance または .balanced または .quality, // instance seg
                            maxNumberPoints: マスク処理ポイントの最大数) // instance seg
        self.model = model
    }
    
}
...

//model?.detect は UIImage を受け取り、その上で推論を実行します
let img = UIImage(named: "example.jpeg") // または CVPixelBuffer
model?.detect(image: img!) { predictions, error in
    if error != nil {
        print(error)
    } else {
        print(predictions)
    }
}
```

**非同期での使い方:**

非同期で使用するには、非同期ブロック内で Roboflow モデルを呼び出す必要があります。

```swift
import Roboflow
...
//API Key で初期化
let rf = RoboflowMobile(apiKey: "API_KEY")
...

//model はあなたのモデルの project 名です
let (model, loadingError, modelName, modelType) = await rf.load(model: "YOUR-MODEL-ID", modelVersion: YOUR-MODEL-VERSION-#)
model!.configure(threshold: threshold, overlap: overlap, maxObjects: maxObjects)
...

//model?.detect は UIImage を受け取り、その上で推論を実行します
let img = UIImage(named: "example.jpeg")
let (predictions, predictionError) = await model!.detect(image: img!)
print(predictions)
```

**Predictions の形式:**

```
x:Float //物体中心の x
y:Float //物体中心の y
width:Float
height:Float
className:String
confidence:Float
color:UIColor
box:CGRect
points:[CGPoint] // インスタンスセグメンテーションモデルのみ
```

[CGRect](https://developer.apple.com/documentation/corefoundation/cgrect)

### ネイティブ Swift の例

この [roboflow-ios-starter](https://github.com/roboflow/roboflow-ios-starter) アプリは、roboflow モデルを使った realtime iOS アプリを作成するための優れた出発点です。これには、カメラ設定、モデルの読み込みと処理、および物体検出モデルとインスタンスセグメンテーションモデルの両方に対応した出力描画コードが含まれています。

### React Native Expo アプリの例

この SDK を React Native の expo アプリに統合する例もこちらで提供しています。独自の downstream アプリケーションの構築を検討する際に役立つでしょう。

必ず次の両方があることを確認してください [Expo](https://docs.expo.dev/) および [CocoaPods](https://guides.cocoapods.org/using/getting-started.html) がインストールされていること。

* `expo-cli` は次の Node.js バージョンをサポートしています: `>=12.13.0 <15.0.0` （Maintenance LTS）および `>=16.0.0 <17.0.0` （Active LTS）
* Node.js 用の yarn パッケージをインストールする必要があります（`npm install -g yarn`)

{% embed url="<https://github.com/roboflow-ai/RoboflowExpoExample>" %}

### iOS アプリケーションの例 - CashCounter

ダウンロード [CashCounter](https://apps.apple.com/app/roboflow-cash-counter/id1633812788)。これは米国の硬貨と紙幣を数えるサンプル iOS アプリで、コンピュータビジョンモデルを iPhone に deploy する方法の例として利用できます。バウンディングボックス、FPS、物体カウント、画像アップロードなどの可視化例を見ることができます。


---

# 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.roboflow.com/roboflow/roboflow-jp/deploy/sdks/ios-sdk.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.
