How to convert Curl to iOS

591 Views Asked by At

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'm trying to get this same command to send some image data with a POST request to my server. I'm confused how to add the "userPic=@" portion of the request to my request. Currently my Swift code is as follows:

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 referenced this stackoverflow post, but I still wasn't able to get it working. I'm confused what I'm doing wrong and if anyone knows the correct way to go about this.

1

There are 1 best solutions below

0
On BEST ANSWER

The main problem is that you can't post image data directly in the HTTPBody without first encoding it as multipart form-data. A good explanation is in the RFC

I have created a simple framework to do this in Swift on github

The basics are that you need to encode it following the RFC before you send it as the body.