Image Upload with Progress Bar example in Swift

In this video tutorial I am going to share how to upload an image and display the upload progress using the UIProgressView.

  • I am going to use UIImagePickerController to let user select one of the images on their device
  • I will use NSMutableURLRequest to send HTTP POST request with image data to a server side PHP script
  • and I will use UIProgressView and well as UILabel to display the upload progress

Video tutorial, source code and links to download project files are below. I hope it helps!

Link to download Image Upload Example with Progress Bar

UIViewController source code:

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate {
@IBOutlet weak var myImageView: UIImageView!
@IBOutlet weak var imageUploadProgressView: UIProgressView!
@IBOutlet weak var progressLabel: UILabel!
@IBOutlet weak var uploadButton: UIButton!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func uploadButtonTapped(sender: AnyObject) {

var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

self.presentViewController(myPickerController, animated: true, completion: nil)

}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])

{
myImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage

myImageView.backgroundColor = UIColor.clearColor()
self.dismissViewControllerAnimated(true, completion: nil)

uploadImage()
}

func uploadImage()
{
let imageData = UIImageJPEGRepresentation(myImageView.image, 1)

if(imageData == nil ) { return }

self.uploadButton.enabled = false

let uploadScriptUrl = NSURL(string:"http://www.swiftdeveloperblog.com/http-post-example-script/")
var request = NSMutableURLRequest(URL: uploadScriptUrl!)
request.HTTPMethod = "POST"
request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")

var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())

var task = session.uploadTaskWithRequest(request, fromData: imageData)
task.resume()

}

func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?)
{
println("didCompleteWithError")

let myAlert = UIAlertView(title: "Alert", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "Ok")
myAlert.show()

self.uploadButton.enabled = true

}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64)
{
println("didSendBodyData")
var uploadProgress:Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)

imageUploadProgressView.progress = uploadProgress
let progressPercent = Int(uploadProgress*100)
progressLabel.text = "\(progressPercent)%"
println(uploadProgress)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void)
{
println("didReceiveResponse")
println(response);
self.uploadButton.enabled = true
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData)
{
println("didReceiveData")
}

}

Source code of PHP script that accepts HTTP POST request with image data, saves image to target directory and sends back JSON response:

$target_dir = "wp-content/uploads/2015/02";

if(!file_exists($target_dir))
{
mkdir($target_dir, 0777, true);
}

$target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) {
echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK"
]);

} else {

echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error"
]);
}