How to Convert Curl in iOS
I have this command that works:
curl -X POST -H -i -F userPic=@/Users/path/to/image.png http://server.com/users/userPic/6
I am writing my program in Swift and I am trying to get this same command to send some image data with a POST request to my server. I am confused how to add the userPic = @ request part to my request. Currently my Swift code looks like this:
func sendUserPicToAPI() {
if let savedId = defaults.stringForKey("UserId") {
userId = savedId.toInt()
}
var imageData = UIImagePNGRepresentation(profPic.image)
var url = NSURL(string: "http://server.com/users/userPic/\(userId)")
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.HTTPBody = NSData(data: imageData!)
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)
let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
println("API Response: \(results)")
}
I have referenced this StackOverflow question but I still haven't been able to get it to work. I am confused as to what I am doing wrong and if anyone knows how to do this correctly.
+3
source to share
1 answer
The main problem is that you cannot post image data directly to the HTTPBody without first being encoded as multipart form-data. A good explanation is in the RFC
I created a simple framework for this at Swift on github
The basics are that you need to encode it after RFC before sending it as body.
+1
source to share