# iOS SDK

Roboflow Mobile iOS SDK는 지연 시간이 더 짧은 추론이나 증강 현실과 같은 새로운 기능, 역량, 사용 사례를 활용하기 위해 엣지(iPad 또는 iPhone)에서 모델이 실행되어야 하는 iOS 애플리케이션을 개발할 때 훌륭한 선택입니다.

맞춤형 컴퓨터 비전 모델이 내장된 네이티브 모바일 애플리케이션은 개발자가 앱에 시각을 부여할 수 있게 해줍니다.

## 작업 지원

다음 작업 유형은 호스팅 API에서 지원됩니다:

| 작업 유형                 | iOS SDK 배포에서 지원 |
| --------------------- | --------------- |
| Object Detection      | ✅               |
| Classification        |                 |
| Instance Segmentation | ✅ (iOS 18 이상)   |
| Semantic Segmentation |                 |

### CoreML Export 호환성

다음 모델 아키텍처는 온디바이스 배포를 위한 CoreML(`.mlpackage`) 내보내기를 지원합니다:

| 모델                | CoreML Export |
| ----------------- | ------------- |
| RF-DETR           | ✅             |
| YoloLite          | ✅             |
| Classification 모델 | ✅             |

## iOS 기기에 모델 배포하기

### 지원되는 하드웨어 및 소프트웨어

모든 iOS 기기는 온디바이스 추론을 지원하지만, iPhone 8(A11 Bionic Processor)보다 오래된 기기는 에너지 효율이 더 낮은 gpu engine으로 대체됩니다.

Roboflow는 최소 iOS 버전 15.4가 필요합니다(Instance Segmentation 모델의 경우 18.0).

## 프로토타이핑

다음에 대해 개발할 수 있습니다. [Roboflow Serverless Hosted API](https://docs.roboflow.com/deploy/serverless). 이 API는 온디바이스 추론과 동일한 학습된 모델을 사용합니다.

## 설치

* 설치 [CocoaPods](https://guides.cocoapods.org/using/getting-started.html) | [문제 해결 가이드](https://guides.cocoapods.org/using/troubleshooting#installing-cocoapods)

"CocoaPods는 Ruby로 빌드되며, macOS에서 기본으로 제공되는 Ruby로 설치할 수 있습니다. Ruby 버전 관리자를 사용할 수도 있지만, 무엇을 하고 있는지 잘 아는 경우가 아니라면 macOS에서 제공되는 표준 Ruby를 사용하는 것을 권장합니다. 기본 Ruby 설치를 사용하면 gem을 설치할 때 `sudo` 를 사용해야 합니다. (다만 이는 gem 설치 중에만 필요한 문제입니다.)" - [CocoaPods](https://guides.cocoapods.org/using/getting-started.html)

"Sudo-less" 설치는 이 과정에서 RubyGems에 관리자 권한을 부여하고 싶지 않을 경우 선택할 수 있는 옵션입니다. 그러나 `sudo` 설치가 더 일반적이라는 점에 유의하세요.

CocoaPods가 성공적으로 설치되었는지 다음을 입력하여 확인하세요 `pod --version` 를 터미널에서.

### Roboflow CocoaPod 설치하기

먼저 다음을 실행하세요 `pod init` 를 프로젝트 디렉터리에서.

다음이 있는지 확인하세요 `Podfile` 이 다음을 지정하는지 `platform :ios, '15.4'`

그다음 다음을 추가하세요 `pod 'Roboflow'` 를 다음에 `Podfile`.

XCode Command Line Tools가 설치되어 있지 않다면 다음을 실행하세요 `xcode-select --install` 를 터미널에서.

그러면 다음이 반환됩니다: `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의 성공적인 설치 후 터미널](/files/f37d0207ddcef8b4cb0ec221c3d95361dad0a205)

![Podfile의 성공적인 설치 후 프로젝트 디렉터리](/files/4d5eb78bddbac1df0f2a0efdb0451b69e2093e41)

* 다음 오류가 반환되면: "You may have encountered a bug in the Ruby interpreter or extension libraries," 먼저 다음을 실행하세요 `brew install cocoapods`, 그다음 다음을 실행하세요 `pod install` 그리고 생성된 `.xcworkspace` 파일을 XCode에서.
  * CocoaPods가 성공적으로 설치되었는지 다음을 입력하여 확인하세요 `pod --version` 를 터미널에서.

### Swift에서 Roboflow 사용하기

다음으로 이동하세요 `.xcworkspace` 파일을 XCode에서.

![](/files/82eb13b1ea5bdb7077d5e44352f516c356b3bbb5)

그다음 다음을 추가하여 Roboflow를 가져오세요 `import Roboflow`.를 `.xcworkspace` 파일에 추가하세요.

그런 다음 다음으로 Roboflow API 인스턴스를 생성하세요 `let rf = Roboflow(apiKey: "API_KEY")`. For `modelVersion`의 경우 다음을 바꾸세요 `YOUR-MODEL-VERSION-#` 를 모델 버전 번호의 정수 값으로.

#### 프로젝트 정보 찾기

**Completion Handler 사용법:**

```swift
import Roboflow
...
//API 키로 초기화
let rf = RoboflowMobile(apiKey: "API_KEY")
var model: RFModel?
...

//model은 모델의 프로젝트 이름입니다
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 or .balanced or .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 키로 초기화
let rf = RoboflowMobile(apiKey: "API_KEY")
...

//model은 모델의 프로젝트 이름입니다
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)
```

**예측 형식:**

```
x:Float // 객체의 중심 x
y:Float // 객체의 중심 y
width:Float
height:Float
className:String
confidence:Float
color:UIColor
box:CGRect
points:[CGPoint] // instance segmentation 모델만 해당
```

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

### 네이티브 Swift 예제

다음 [roboflow-ios-starter](https://github.com/roboflow/roboflow-ios-starter) 앱은 roboflow 모델로 실시간 iOS 앱을 만들기 위한 훌륭한 출발점입니다. 여기에는 Object Detection 및 Instance Segmentation 모델 모두에 대한 카메라 설정, 모델 로딩 및 처리, 출력 그리기 코드가 포함되어 있습니다.

### React Native Expo 앱 예제

또한 여기에서 React Native를 사용해 이 SDK를 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)
* yarn 패키지는 Node.js용으로 설치되어 있어야 합니다(`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에 배포하는 방법의 예시입니다. 바운딩 박스 시각화, 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-ko/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.
