我知道这个问题之前已经被问过几次了,here , here并可能有更多次。我已经尝试了所有这些答案,但没有一个适合我想做的事情。
本质上,我正在尝试将 UIImage 连接到 Kairos API
。我正在发出一个简单的 POST 请求,并在请求中使用 source
参数。该请求返回一个 JSON 对象,其中包含我想在应用程序中使用的各种数据点。我看到的关于上传图像文件的大多数答案都使用 multipart-form-data
请求来执行此操作,但我不确定这将如何连接到源
code> API 在请求中要求的参数。我知道如何将身份验证部分作为 header 添加到我的 URLRequest
中,我只需要帮助将图像作为 source
参数上传。
此CURL
代码有效:
curl -X POST -H "app_id: XXX" -H "app_key: YYY" -F "source=@/Users/myusername/Desktop/myimage.jpg" "https://api.kairos.com/v2/media"
但是,我不确定如何将此类代码转换为 Swift。
最好,我想使用传统的 URLRequests 和 URLSessions
而不是第三方外部库(因为我读过的几篇博客文章提到了使用第三方的危险)有时聚会图书馆)。谁能帮我做到这一点?
提前致谢!
最佳答案
代码应该像这样。
let url = URL(string: "https://api.kairos.com/v2/media")
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = "POST"
urlRequest.addValue("XXX", forHTTPHeaderField: "app_id")
urlRequest.addValue("YYY", forHTTPHeaderField: "app_key")
let boundary = "Boundary-\(UUID().uuidString)"
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
//image data
let image = UIImage() //replace with your image
let fileName = "myimage.jpg"
let data = UIImageJPEGRepresentation(image, 0.7)!
//create body
let body = NSMutableData()
//append first line
let line1_boundryPrefix = "--\(boundary)\r\n"
body.append(line1_boundryPrefix.data(
using: String.Encoding.utf8,
allowLossyConversion: false)!)
//append second line
let line2_parameter = "Content-Disposition: form-data; name=\"source\"; filename=\"" + fileName + "\"\r\n"
body.append(line2_parameter.data(
using: String.Encoding.utf8,
allowLossyConversion: false)!)
//append third line (mime type)
let mimeType = "image/jpg"
let line3_contentType = "Content-Type: \(mimeType)\r\n\r\n"
body.append(line3_contentType.data(
using: String.Encoding.utf8,
allowLossyConversion: false)!)
//append image data
//line4
body.append(data)
let line5 = "\r\n"
body.append(line5.data(
using: String.Encoding.utf8,
allowLossyConversion: false)!)
let line6 = "--" + boundary + "--\r\n"
body.append(line6.data(
using: String.Encoding.utf8,
allowLossyConversion: false)!)
urlRequest.httpBody = body as Data
urlRequest.setValue(String(body.length), forHTTPHeaderField: "Content-Length")
URLSession.shared.dataTask(with: urlRequest) { (data, urlResponse, error) in
//handle callback
}
关于ios - 如何使用 Swift 将 UIImage 作为 swift3 中的 'source=' 参数上传到 REST API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47056982/