1. Home
  2. Docs
  3. PixelSnapAI Documentation
  4. Example Code
  5. Swift

Swift

# PixelSnapAI API Swift Example

This documentation provides an example code snippet in Swift for using the PixelSnapAI API to upload and analyze an image. Follow the steps below to run the code successfully.

## Prerequisites

Before running the code, ensure that you have the following:

- Xcode installed on your system.

## Code Example

```swift
import Foundation

func uploadAndAnalyzeImage() {
    let url = URL(string: "URL_END_POINT")!
    let token = "[SECRET_KEY]"
    let image = UIImage(named: "product_img.jpeg")!
    let imageData = image.jpegData(compressionQuality: 1.0)!
    
    let boundary = UUID().uuidString
    let fieldName = "picture"
    let fileName = "product_img.jpeg"
    let mimeType = "image/jpeg"
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    request.addValue("Token \(token)", forHTTPHeaderField: "Authorization")
    
    var body = Data()
    
    // Add image data
    body.append("--\(boundary)\r\n".data(using: .utf8)!)
    body.append("Content-Disposition: form-data; name=\"\(fieldName)\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
    body.append("Content-Type: \(mimeType)\r\n\r\n".data(using: .utf8)!)
    body.append(imageData)
    body.append("\r\n".data(using: .utf8)!)
    
    body.append("--\(boundary)--\r\n".data(using: .utf8)!)
    
    request.httpBody = body
    
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let error = error {
            print("Error: \(error)")
            return
        }
        
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
                if let json = json {
                    let message = json["message"] as? String
                    let productNames = json["product_name"] as? [String]
                    print("Message: \(message ?? "")")
                    print("Product Names: \(productNames ?? [])")
                }
            } catch {
                print("Error: \(error)")
            }
        }
    }
    
    task.resume()
}

uploadAndAnalyzeImage()

Running the Code

Follow these steps to run the provided code:

  1. Open Xcode or your preferred Swift development environment.
  2. Create a new Swift project or open an existing one.
  3. Copy and paste the code into a Swift file in your project.
  4. Make sure you have the image file product_img.jpeg added to your project.
  5. Replace the placeholder value URL_END_POINT in the url variable with the actual PixelSnapAI API endpoint URL.
  6. Replace the placeholder value [SECRET_KEY] in the token variable with your actual PixelSnapAI API token. This token can be obtained from your PixelSnapAI account after subscribing to a plan.
  7. Build and run the project using the simulator or a physical device.
  8. The code will send a POST request to the PixelSnapAI API, uploading the image and returning the response.
  9. The response will be printed to the console, displaying the analysis results or any error messages received from the API.

Return Example

When the API request is successful, the code will receive a JSON response similar to the following:

jsonCopy code{
    "message": "Picture uploaded successfully.",
    "product_name": [
        "Dualshock 4",
        "PS4 DualShock 4",
        "Pro Wireless GamePad",
        "Nuc Controller Plus"
    ]
}

The returned JSON includes a "message" field indicating the success status and a "product_name" field containing a list of product names extracted from the uploaded picture.

Make sure to adjust the code as needed to handle the response according to your application’s requirements.

Conclusion

You have successfully run the Swift example code for utilizing the PixelSnapAI API to upload and analyze an image. This code demonstrates the process of making a POST request to the API endpoint and handling the response.

For further information on the available API endpoints, request parameters, and response formats, please refer to the official PixelSnapAI API documentation on the PixelSnapAI website.

If you encounter any issues or have additional questions, please contact our support team at info@pixelsnapai.com. We are here to assist you!

Was this article helpful to you? Yes No

How can we help?