Last active
October 10, 2016 16:26
-
-
Save paulmars/edf461ab2e049271efe5f7ddb36ff70b to your computer and use it in GitHub Desktop.
Image Upload to Rails 5 w/ Swift 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ImageUploader.swift | |
// | |
// Created by Paul McKellar on 10/9/16. | |
// Copyright © 2016 Paul McKellar. All rights reserved. | |
// | |
import Foundation | |
class ImageUploader: NSObject { | |
init(data: Data) { | |
super.init() | |
self.startProcess(data) | |
return | |
} | |
func startProcess(_ data: Data) -> Void { | |
let manqueue = OperationQueue.main | |
let configuration = URLSessionConfiguration.ephemeral | |
configuration.urlCache = nil | |
configuration.httpCookieAcceptPolicy = .never | |
configuration.httpCookieStorage = nil | |
let session = URLSession(configuration: configuration, delegate:nil, delegateQueue: manqueue) | |
let url = URL(string:"\(ApiRequest.URLBase)/api/v1/assets.json")! | |
let request:NSMutableURLRequest = NSMutableURLRequest(url: url, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 15) | |
let FORM_BOUNDARY:String = "Boundary-\(NSUUID().uuidString)" | |
let multipartBoundary:String = "--\(FORM_BOUNDARY)" | |
let endBoundary:String = "\(multipartBoundary)--" | |
let body:NSMutableString = NSMutableString() | |
body.appendFormat("%@\r\n",multipartBoundary) | |
body.appendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"o.png\"\r\n") | |
body.appendFormat("Content-Type: image/png\r\n\r\n") | |
let end:String = "\r\n\(endBoundary)" | |
let requestData:NSMutableData = NSMutableData(); | |
requestData.append(body.data(using: String.Encoding.utf8.rawValue)!) | |
requestData.append(data) | |
requestData.append(end.data(using: String.Encoding.utf8)!) | |
let content:String = "multipart/form-data; boundary=\(FORM_BOUNDARY)" | |
request.setValue(content, forHTTPHeaderField: "Content-Type") | |
request.setValue("\(requestData.length)", forHTTPHeaderField: "Content-Length") | |
request.httpBody = requestData as Data | |
request.httpMethod = "POST" | |
let task = session.dataTask(with: request as URLRequest, completionHandler: { | |
data, response, error in | |
if error != nil { | |
print("BLUR!!! \(error)") | |
} | |
else { | |
print("BLUR!!! \(data)") | |
print("BLUR!!! \(response)") | |
} | |
}) | |
task.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hacked this together in 3 minutes.
This worked at least once, which is more than I can say for everything else on the internet.
Intended to be sparse/helpful. Can change delegate to self and not use closures.