Sanjay
Sanjay

Reputation: 203

How to send an image via a POST request in Swift 4?

func createPost(username: String, user_id: String, description: String, image: UIImage, completion: @escaping (Bool) -> ()) {
    var request = URLRequest(url: URL(string: Globals.root+"/amazing/image/post/here")!)
    request.httpMethod = "POST"
    //request.httpBody = .data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }
        if let data = data {
            do {
                let aaData = try JSONSerialization.jsonObject(with: data, options: [])
                if let ppData = aaData as? [String:Any] {
                    let u = ppData["username"] as! Bool
                    if u == true {
                        completion(true)
                    }
                }
            } catch let error as NSError {
                print(error.localizedDescription)
                completion(false)
            }
        }
    }
    task.resume()
}

I've been searching and searching for a valid answer and I haven't found any that pertains to Swift 4. I want to be able to send an image to my RESTful API without encoding it. How can one do that? Thanks in advance. : )

Upvotes: 1

Views: 2391

Answers (1)

Mitchell Currie
Mitchell Currie

Reputation: 2809

First off, given the fact you're sending username, and stuff along with image, it must be a multipart form (or some ugly BASE64 encoded JSON property).

Typically speaking, clean way to do this is upload image first via binary body post (as the image is the sole thing in transfer and is faster too), obtain the Id and reference it as a field.

Failing this, it's quite hard, how about using Moya + AlamoFire?

https://github.com/Moya/Moya/issues/598

An image is a binary object, and this not valid HTTP unless you either encode it via multipart form or wrap it JSON safe Base-64 (assuming you are using JSON)

Upvotes: 1

Related Questions