2

I need to upload an image to the server endpoint where the structure has to be as following:

    {
        "name": "",
        "description": "",
        "photo": imageFile
    }

How can I send such a request using Alamofire?

I tried this but the result is error with error message Invalid type in JSON write (NSConcreteData) This is my code :

    let imageData = UIImagePNGRepresentation(image)
    let base64String = imageData!.base64EncodedDataWithOptions([])
    
    let parameters = [
        "name": "name",
        "description": "desc",
        "photo": base64String
    ]
    
    let credentialData = "\(id):\(secret)".dataUsingEncoding(NSUTF8StringEncoding)!
    let base64Credentials = credentialData.base64EncodedStringWithOptions([])
    let headers = ["Authorization": "Basic \(base64Credentials)"]

    Alamofire.request(.POST, "", parameters: parameters, encoding: .JSON, headers: headers).responseJSON { (response) -> Void in
        print(response)
    }

And I followed this code

If there is another way to do please advice, thanks.

1
  • try using base64EncodedStringWithOptions instead of base64EncodedDataWithOptions Commented Mar 6, 2016 at 4:09

1 Answer 1

1

This method I'm using you might find it useful

let image : UIImage = image.image!
let imageData = UIImagePNGRepresentation(image)
let base64String = imageData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
Sign up to request clarification or add additional context in comments.

3 Comments

Wow, thanks it works. I wanna ask what is the Encoding64CharacterLineLength, can i replace it with an empty array?
no you can't. it's a method that convert image data to long string that you can append to JSON and send as parameters
you can create a different array and append base64 string to it and send

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.