Вот код Python, который мне нужно было переписать:
Код: Выделить всё
import json
import requests
# Run inference on an image
url = "URL"
headers = {"x-api-key": "Token"}
data = {"model": "Specific model"}
with open("image.jpg", "rb") as f:
response = requests.post(url, headers=headers, data=data, files={"file": f})
# Check for successful response
response.raise_for_status()
# Print inference results
print(json.dumps(response.json(), indent=2))
Код: Выделить всё
import UIKit
func uploadImage(photo: UIImage) async {
// Define the API endpoint and your API key
let apiURL = URL(string: "URL")!
let apiKey = "Token"
guard let imageData = photo.jpegData(compressionQuality: 1.0) else {
print("Could not convert image to JPEG data.")
return
}
// Create the URL request
var request = URLRequest(url: apiURL)
request.httpMethod = "POST"
request.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
request.setValue(apiKey, forHTTPHeaderField: "x-api-key")
// Create the JSON payload
let base64Image = imageData.base64EncodedString()
let jsonPayload: [String: Any] = [
"model": "Specific model",
"file": base64Image
]
guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonPayload) else {
print("Could not serialize JSON data.")
return
}
request.httpBody = jsonData
// Perform the network request
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
guard let data = data else {
print("No data received.")
return
}
// Handle the response
do {
if let jsonResponse = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
print("Response JSON: \(jsonResponse)")
return
// Parse and use the response data
}
} catch let jsonError {
print("JSON Error: \(jsonError.localizedDescription)")
return
}
}
task.resume()
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... in-swiftui