Swift: Upload images using NSURLSession (NSInputStream)


This is a very simple example of using a stream to upload where all the parameters are known to us.

PHP

The PHP file looks like this:
<?php
// choose a filename
$filename = "new_image.jpg";

// access the input stream via php://input
$input = fopen('php://input', 'rb');
$file = fopen($filename, 'wb'); 

stream_copy_to_stream($input, $file);
fclose($input);
fclose($file);
?>

Swift

And the Swift looks like this:
// delegate for receiving data
class SessionDelegate:NSObject, NSURLSessionDataDelegate, NSURLSessionTaskDelegate {
    func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: (NSInputStream?) -> Void) {
        if let fileURL = NSBundle.mainBundle().URLForResource("image", withExtension: "jpg"),
            path = fileURL.path,
            inputStream = NSInputStream(fileAtPath: path)
        {
            
            completionHandler(inputStream)
        }
        
    }

}
// create a background session configuration with identifier
let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("myConfig")

if let url = NSURL(string: "http://127.0.0.1:8888/image_upload.php") {
    let delegate = SessionDelegate()
    // create session by instantiating with configuration and delegate
    let session = NSURLSession(configuration: config, delegate: delegate, delegateQueue: nil)
    
    let request = NSMutableURLRequest(URL: url)
    
    request.HTTPMethod = "POST"
    
    let uploadTask = session.uploadTaskWithStreamedRequest(request)
    
    uploadTask.resume()
    
}
Now with a file in place of the name "image.jpg" you should be able with the help of MAMP or another type of server to be able to upload and save an image. Note how the content for the stream is accessed via a delegate method, as instructed by the docs for uploadTaskWithStreamedRequest.

Notice how the file is provided within the delegate rather than beforehand.

Comments