Skip to content

Instantly share code, notes, and snippets.

@Vadbeg
Last active November 5, 2022 12:18
Show Gist options
  • Save Vadbeg/118b686aedc796f1b8dd17e4e9ccc488 to your computer and use it in GitHub Desktop.
Save Vadbeg/118b686aedc796f1b8dd17e4e9ccc488 to your computer and use it in GitHub Desktop.
send_request.swift
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
var semaphore = DispatchSemaphore (value: 0)
let parameters = [
[
"key": "image",
"src": "/Users/vadim.tsitko/Downloads/IMG_2218 2.jpeg",
"type": "file"
]] as [[String : Any]]
let boundary = "Boundary-\(UUID().uuidString)"
var body = ""
var error: Error? = nil
for param in parameters {
if param["disabled"] == nil {
let paramName = param["key"]!
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"\(paramName)\""
if param["contentType"] != nil {
body += "\r\nContent-Type: \(param["contentType"] as! String)"
}
let paramType = param["type"] as! String
if paramType == "text" {
let paramValue = param["value"] as! String
body += "\r\n\r\n\(paramValue)\r\n"
} else {
let paramSrc = param["src"] as! String
let fileData = try NSData(contentsOfFile:paramSrc, options:[]) as Data
let fileContent = String(data: fileData, encoding: .utf8)!
body += "; filename=\"\(paramSrc)\"\r\n"
+ "Content-Type: \"content-type header\"\r\n\r\n\(fileContent)\r\n"
}
}
}
body += "--\(boundary)--\r\n";
let postData = body.data(using: .utf8)
var request = URLRequest(url: URL(string: "https://api.aimagic-app.com/v1/colorize")!,timeoutInterval: Double.infinity)
request.addValue("API_KEY", forHTTPHeaderField: "x-access-token")
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
semaphore.signal()
return
}
print(String(data: data, encoding: .utf8)!)
semaphore.signal()
}
task.resume()
semaphore.wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment