-1

I'm trying to send an uploaded image to server. I'm getting the image from photos successfully, and I'm attaching it to a UIImageView in ViewController. Now I need to send this image to server along with other data. I'm able to send all data successfully except the image.

Here is my func:

func placeOrder(withOrder: Order) {

    let returnedJobId: String? = UserDefaults.standard.object(forKey: "jobId") as? String
    let returnedOrderPrice: String? = UserDefaults.standard.object(forKey: "orderPrice") as? String

    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let currentDateTime  = formatter.string(from: Date())
    let selectedImage = imagePlaceHolder.image!
    let uploadedFile = selectedImage.jpegData(compressionQuality: 0.5)
    DispatchQueue.main.async {

        let date     = self.chosenTimeDateTextFieldDisplay.text!    
        let address  = self.addressField.text!
        let phone    = self.phoneField.text!
        let comments = self.commentsEntryView.text!
        let file     = uploadedFile
        let jobId    = returnedJobId!
        let price    = returnedOrderPrice!

        let headers = [
            "content-type" : "multipart/form-data",//application/x-www-form-urlencoded",
            "cache-control": "no-cache",
            "postman-token": "dded3e97-77a5-5632-93b7-dec77d26ba99"
        ]

        let user = CoreDataFetcher().returnUser()
        let provider = user.provider_id
        let userID = user.id
        let userType = user.user_type

        let postData = NSMutableData(data: "data={\"user_type\":\"\(userType)\",\"job_id\":\"\(jobId)\",\"user_id\":\"\(userID)\",\"provider_id\":\"\(provider)\",\"order_placing_time\":\"\(currentDateTime)\",\"order_start_time\":\"\(date)\",\"order_address\":\"\(address)\",\"order_phone\":\"\(phone)\",\"order_comments\":\"\(comments)\",\"order_price\":\"\(price)\",\"$_FILES\":\"\(file!)\"}".data(using: String.Encoding.utf8)!)

        let request = NSMutableURLRequest(url: NSURL(string: "http://Api/v2/placeOrder")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                          timeoutInterval: 10.0)

        request.httpMethod          = "POST"
        request.allHTTPHeaderFields = headers
        request.httpBody            = postData as Data

        let session  = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
            if (error != nil) {
                print(error!)
            } else {
                if let dataNew = data, let responseString = String(data: dataNew, encoding: .utf8) {
                    print(responseString)

                    DispatchQueue.main.async {
                        do {
                            let fetcher = CoreDataFetcher()
                            let json = try JSON(data: data!, options: .allowFragments)
                            let answer = json["answer"]
                            let status = json["status"]
                            let orderID = answer.int!

                            if status == "ok" {
                                print("Status is OK")
                            }

                            fetcher.addOrderID(orderId: orderID, toOrder: withOrder)
                            print("Order id has been saved!")
                        } catch {
                            print("Order ID Counldn't be Saved!")
                        }
                    }

                }

            }
        })

        dataTask.resume()
    }

}

This method isn't working. as it should be made a multipart form data

How to rewrite my func to be a multipart form data to convert the image to PNG file and attach it in the API request?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Jessica Kimble
  • 493
  • 2
  • 7
  • 17
  • Send it as jpeg. Your issue is probably the file size limit your server might impose. – Leo Dabus Jul 19 '19 at 12:58
  • Image or File will be send as `Data` along with its `mime type` to server. In your case mime type is `image/png`. The print description is correct. What is wrong here and what do you expect? – TheTiger Jul 19 '19 at 12:58
  • related https://stackoverflow.com/questions/29137488/how-do-i-resize-the-uiimage-to-reduce-upload-image-size/29138120?r=SearchResults&s=2|62.3897#29138120 and https://stackoverflow.com/questions/29726643/how-to-compress-of-reduce-the-size-of-an-image-before-uploading-to-parse-as-pffi/29726675 – Leo Dabus Jul 19 '19 at 13:01

1 Answers1

0

The answer to your question strongly depends on how you are trying to send your data to server. Ironically you have provided no information about that at all. If this is JSON based API then two most likely solutions are:

  • You will need to convert your data to base64 string
  • You will need to send a multipart form data

This should all be covered somewhere in the documentation of your API. For base64 things are very simple; you can use image.pngData()?.base64EncodedString(). The multipart form data is a bit more complicated but you can find a lot of posts on it like this one.

For non-JSON I guess you could just POST raw data with correct content type header. But this again depends on the API implementation.

In any case you could also try to find what the error is if any.

Matic Oblak
  • 16,318
  • 3
  • 24
  • 43