The Bao
The Bao

Reputation: 129

Uploading Image to API Server using Alamofire

I have a question about Uploading Image to API server using Alamofire.

BaseURL: http://vietnamtravelguide-app.com/quangnam/api_inquangnam/tips/create?user_id=""&token="" 3 parameters : location_id, content, imageName

It's ok to post by POSTMAN

It's ok to post by POSTMAN

My Code:

Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(image, withName: "imageName", fileName: "swift_file.jpeg", mimeType: "image/jpeg")

        }, with: path, encodingCompletion: {encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
            upload.responseJSON { response in
                print(response.result)
            switch response.result {
            case .success:
                let json = JSON(response.result.value!)
                if(delegate != nil) {
                    delegate!.didReceiveResult(json,basePath: basePath)
                }
            case .failure(let error):
                print(error)
            }                        }
            case .failure(let encodingError):
                print(encodingError)
            }

            })

with image ( image from parameter casting as Data). When I debug it , i got response.result return failure

Upvotes: 0

Views: 1649

Answers (1)

Rajan Maheshwari
Rajan Maheshwari

Reputation: 14571

You are not uploading the remaining two parameters content and location_id.

Try this one and see the result. I have also used SwiftyJSON here.

This is my APIManager class for all APIs handling.

import Alamofire
import SwiftyJSON

class APIManager: NSObject {

    class func apiMultipart(serviceName:String,parameters: [String:Any]?, completionHandler: @escaping (JSON?, NSError?) -> ()) {

        Alamofire.upload(multipartFormData: { (multipartFormData:MultipartFormData) in
            for (key, value) in parameters! {
                if key == "imageName" {
                    multipartFormData.append(
                        value as! Data,
                        withName: key,
                        fileName: "swift_file.jpg",
                        mimeType: "image/jpg"
                    )
                } else {
                    //Data other than image
                    multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
                }
            }
        }, usingThreshold: 1, to: serviceName, method: .post, headers: ["yourHeaderKey":"yourHeaderValue"]) { (encodingResult:SessionManager.MultipartFormDataEncodingResult) in

            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    if response.result.error != nil {
                        completionHandler(nil,response.result.error as NSError?)
                        return
                    }
                    print(response.result.value!)
                    if let data = response.result.value {
                        let json = JSON(data)
                        completionHandler(json,nil)
                    }
                }
                break

            case .failure(let encodingError):
                print(encodingError)
                completionHandler(nil,encodingError as NSError?)
                break
            }
        }
    }
}

If you don't have any header then you can leave the field as ["":""] in place of your ["yourHeaderKey":"yourHeaderValue"]

Now in order to call I just formed the parameters in the controller.

var params = [String:AnyObject]()
params["content"] = "something" as AnyObject?
params["location_id"] = "201" as AnyObject?

// Grab your image from some variable or imageView. Here self.profileImage is a UIImage object
if let profileImageData = self.profileImage {
    if let imageData = UIImageJPEGRepresentation(profileImageData, 0.5) {
        params["imageName"] = imageData as AnyObject?
        APIManager.apiMultipart(serviceName: "http://yourAPIURL", parameters: params, completionHandler: { (response:JSON?, error:NSError?) in
        //Handle response       
        })
    } else {
       print("Image problem")
    }
}

Upvotes: 5

Related Questions