Skip to content

Instantly share code, notes, and snippets.

@imaizume
Created September 19, 2025 14:10
Show Gist options
  • Select an option

  • Save imaizume/37910cf3cc1cedb602e4f74d55704ab3 to your computer and use it in GitHub Desktop.

Select an option

Save imaizume/37910cf3cc1cedb602e4f74d55704ab3 to your computer and use it in GitHub Desktop.
iOSDC Japan 2025 発表関連のコード
//
// Request.swift
// VisionFrameworkDemo
//
// Created by tomohiro-imaizumi on 2025/09/19.
//
import CoreGraphics
import Vision
/// iOS17までの書き方
func performLegacyDetectionRequest(
cgImage: CGImage,
orientation: CGImagePropertyOrientation
) async throws -> [CGRect] {
let request = VNDetectFaceRectanglesRequest()
request.preferBackgroundProcessing = true
// シミュレーターではCPUを使用
#if targetEnvironment(simulator)
if #available(iOS 17.0, *) {
let allDevices = MLComputeDevice.allComputeDevices
for device in allDevices {
if device.description.contains("MLCPUComputeDevice") {
request.setComputeDevice(.some(device), for: .main)
break
}
}
} else {
request.usesCPUOnly = true
}
#endif
let handler = VNImageRequestHandler(
cgImage: cgImage,
orientation: orientation
)
return try await withTaskCancellationHandler {
try Task.checkCancellation()
return try await withCheckedThrowingContinuation { continuation in
do {
try handler.perform([request])
continuation.resume(
returning: (request.results ?? []).map {
VNImageRectForNormalizedRect($0.boundingBox, Int(cgImage.width), Int(cgImage.height))
}
)
} catch {
continuation.resume(throwing: error)
}
}
} onCancel: {
request.cancel()
}
}
/// iOS18以降での書き方
@available(iOS 18.0, *)
func performDetectionRequest(
cgImage: CGImage,
orientation: CGImagePropertyOrientation
) async throws -> [CGRect] {
let request = DetectFaceRectanglesRequest()
let size: CGSize = .init(width: Int(cgImage.width), height: Int(cgImage.height))
return try await request
.perform(on: cgImage, orientation: orientation)
.map {
$0.boundingBox.toImageCoordinates(size, origin: .upperLeft)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment