Skip to content

Instantly share code, notes, and snippets.

@Gujci
Created June 11, 2016 20:04
Show Gist options
  • Save Gujci/e6608f207b53e981f7871615d2b2bd5c to your computer and use it in GitHub Desktop.
Save Gujci/e6608f207b53e981f7871615d2b2bd5c to your computer and use it in GitHub Desktop.
static func uploadData(endpoint: NSURL, binaryData: NSData,
boundary: String = "defaultBoundary", data: Dictionary<String, AnyObject>? = nil, done: ((NSError?, JSON) -> Void)? = nil)
{
// create url request to send
let mutableURLRequest = NSMutableURLRequest(URL: endpoint)
mutableURLRequest.HTTPMethod = "PUT"
let boundaryConstant = boundary;
let contentType = "multipart/form-data;boundary="+boundaryConstant
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
// create upload data to send
let uploadData = NSMutableData()
// add image
uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Disposition: form-data; name=\"image\"; filename=\"file.png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData(binaryData)
// add parameters
if let params = data {
for (key, value) in params {
uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
}
}
uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
mutableURLRequest.HTTPBody = uploadData
NSURLConnection.sendAsynchronousRequest(mutableURLRequest, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
//TOOD: add completion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment