Вы можете выполнить несколько шагов для обнаружения лиц по изображению.
Создать свой URLRequest
func createRequest() -> URLRequest? {
// Create your request URL
if let url = URL(string: "YOUR_API_KEY") {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(Bundle.main.bundleIdentifier ?? "", forHTTPHeaderField: "X- Ios-Bundle-Identifier")
let jsonRequest = [
"requests": [
"features": [
[
"type": "FACE_DETECTION",
"maxResults": 10 //change as per your requirement
]
]
]
]
let jsonData = try? JSONSerialization.data(withJSONObject: jsonRequest)
request.httpBody = jsonData
return request
}
return nil
}
Запустить запрос в фоновом режимепоток
let task: URLSessionDataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "")
return
}
print(data)// Analyze with this data
}
task.resume()
Анализ данных (в главном потоке, если вы хотите обновить какой-либо компонент пользовательского интерфейса)
DispatchQueue.main.async(execute: {
do {
guard let json =
try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { return }
guard let responses = json["responses"] as? NSArray else { return }
if responses.count > 0 {
guard let response = responses.firstObject as? [String: Any] else { return }
guard let faceAnnotations = response["faceAnnotations"] as? NSArray else {
print(false, "No face detected, please try another photo.")
return
}
if faceAnnotations.count > 0 {
print("Face successfully detected: \(faceAnnotations.count)")
} else {
print("No face detected, please try another photo.")
}
} else {
print("Error while face detection process, please try again.")
}
} catch {
print("Error while face detection process, please try again.")
}
})