Перейти к основному содержимому

iOS SDK

Добавьте AR Clip VPS в нативное iOS-приложение. SDK с помощью отслеживания ARKit определяет положение пользователя на ваших VPS-картах. Это XCFramework, который работает в приложениях на UIKit, RealityKit и SwiftUI.

Что нужно​

  • iOS 15.0 или новее
  • Xcode 14 или новее (Swift 5.7 или новее)
  • Устройство с поддержкой ARKit. Симулятор не поддерживается.

Установка​

Есть два способа.

Swift Package Manager​

  1. В Xcode выберите File → Add Packages….
  2. Введите https://github.com/WebAR-Studio/was-vps-ios.git.
  3. Выберите нужную ветку или тег и добавьте пакет в свой таргет.

Вручную​

  1. Клонируйте репозиторий:
    git clone https://github.com/WebAR-Studio/was-vps-ios.git
  2. Перетащите WASVPS.xcframework в проект.
  3. В General → Frameworks, Libraries, and Embedded Content проверьте, что фреймворк встраивается в приложение.

Разрешения​

Добавьте в Info.plist описания доступа к камере и геопозиции, чтобы iOS могла запросить их у пользователя.

<key>NSCameraUsageDescription</key>
<string>This app requires access to the camera to display augmented reality content.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to your location to place AR content accurately.</string>
<key>NSLocationTemporaryUsageDescriptionDictionary</key>
<dict>
<key>VPSLocalization</key>
<string>Enable precise location for accurate AR content positioning.</string>
</dict>

Запуск VPS​

Вызовите VPSBuilder.initializeVPS, чтобы создать VPSService. Передайте ARSession, свой API-ключ и ID локаций.

Нужен API-ключ?

Получите его на arclip.design или напишите на support@arclip.design.

import ARKit
import WASVPS

final class VPSDemoController: UIViewController, ARSCNViewDelegate {
@IBOutlet private weak var sceneView: ARSCNView!
private var configuration: ARWorldTrackingConfiguration?
private var vps: VPSService?

override func viewDidLoad() {
super.viewDidLoad()
sceneView.delegate = self
sceneView.scene = SCNScene()

configuration = VPSBuilder.getDefaultConfiguration()

VPSBuilder.initializeVPS(
arSession: sceneView.session,
apiKey: "your-api-key",
locationIds: ["your-location-id"],
url: "https://api.arclip.app/vps/api/v3",
gpsUsage: false,
delegate: self
) { service in
self.vps = service
self.vps?.start()
}
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let configuration { sceneView.session.run(configuration) }
}

func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
vps?.frameUpdated()
}
}

extension VPSDemoController: VPSServiceDelegate {
func positionVPS(pos: ResponseVPSPhoto) {
print("Localized pose:", pos)
}

func error(err: NSError) {
print("VPS error:", err)
}

func sending(requestData: UploadVPSPhoto?) {
print("Sending localization request…")
}
}

Ставьте сервис на паузу в sessionWasInterrupted и запускайте снова в sessionInterruptionEnded.

RealityKit​

С RealityKit передавайте кадры в ARSessionDelegate:

func session(_ session: ARSession, didUpdate frame: ARFrame) {
vps?.frameUpdated()
}

Вызовы жизненного цикла (start, stop, clearCustomLocPos) такие же, как со SceneKit.

SwiftUI​

Оберните ARSCNView или ARView в UIViewRepresentable или UIViewControllerRepresentable. Храните VPSService в общей модели представления и вызывайте start() / stop() из элементов управления SwiftUI.

Дополнительные возможности​

  • Передайте известную трансформацию перед первой локализацией через setCustomLocPosForFirstRequest.
  • Чтобы использовать другой адрес сервера, передайте в initializeVPS другой url.
  • Включите gpsUsage, чтобы добавлять в запросы координаты устройства.

Решение проблем​

  • Если VPSBuilder.getDefaultConfiguration() возвращает nil, устройство не поддерживается.
  • Если колбэки не приходят, проверьте, что frameUpdated() вызывается каждый кадр, а API-ключ и ID локаций верные.
  • Примеры для UIKit, RealityKit и SwiftUI — в папке /examples.