如何使用 Swift 将 UIImage 上传到 REST API,作为 swift3 中的 'source=' 参数?

How can I upload a UIImage to an REST API using Swift, as a 'source=' parameter in swift3?

我知道这个问题已经被问过几次了,here, here可能还有很多次。我已经尝试了所有这些答案,但其中 none 对我正在尝试做的事情有效。

本质上,我正在尝试将 UIImage 连接到 Kairos API。我正在发出一个简单的 POST 请求,请求中有一个 source 参数。请求 returns a JSON object 带有我想在我的应用程序中使用的各种数据点。我看到的关于上传图像文件的大多数答案都使用 multipart-form-data 请求来执行此操作,但我不确定这将如何连接到 API 的 source 参数在请求中请求。我知道如何将身份验证部分作为 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 and URLSessions 而不是 third-party 外部库(由于我读过的几篇博客文章提到了使用 [=36 的危险=] 图书馆)。谁能帮我做这个?

提前致谢!

代码应该是这样的。

        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
        }