Today,  I will share how to make a Camera App, and store the clicked Selfie and upload the image on online server.

Prerequisite Skills :

  1. Basics of iOS Programming.
  2. Use of Alamofire (A networking library to post the data on online database
  3. Have basics understanding of PHP and MySQL as we are going to use the same for our backend.

Here in this tutorial what our App will do is to click a picture through launching the Camera module and after confirming it will directly upload it to the online server and for filename reference it will store the filename and other details on online database.

Steps :

  1. Just add a Button on which we will perform the Camera Action.
  2. Then need to manually add following delegate.

    UIImagePickerControllerDelegate, UINavigationControllerDelegate

  3. Need to generate the unique name for each pictures so we will use it with the combination of appending date and time.
  4. And finally need to add few codes for imagePickerController
  5. To prevent the code from crash, we also need to add code for the device with no camera.We will generate the name for each individual pictures by storing the combination of date and time on overriding the viewDidAppear function.

    let tcalendar = NSCalendar.current
    let tdate = NSDate()
    let day = tcalendar.component(.day, from: tdate as Date)let month = tcalendar.component(.month, from: tdate as Date)
    let year = tcalendar.component(.year, from: tdate as Date)
    let hour = tcalendar.component(.hour, from: tdate as Date)
    let minute = tcalendar.component(.minute, from: tdate as Date)
    let seconds = tcalendar.component(.second, from: tdate as Date)
    filenameDate = "\(year)\(month)\(day)"
    filenameTime = "\(hour)\(minute)\(seconds)"
    filename = filenameDate + filenameTime
    Now it’s time to add code in imagePickerController function.
    func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : AnyObject]){chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //2
    dismiss(animated:true, completion: nil) //5
    let imageData = UIImageJPEGRepresentation(chosenImage, 0.7)
    multipartFormData:{ multipartFormData in
    multipartFormData.append(imageData!, withName: "userfile",fileName: self.filename ,mimeType: "image/*")
    multipartFormData.append( String.Encoding.utf8, allowLossyConversion: false)!, withName: "imgdesc")
    }, usingThreshold:UInt64.init(),
    encodingCompletion: { encodingResult in
    switch encodingResult {
    case .success(let upload, _, _):
    upload.responseJSON { response in
    case .failure(let encodingError):

    Now it’s time to launch the Camera action on button click event.

    if UIImagePickerController.isSourceTypeAvailable(.camera) {
    picker.allowsEditing = false
    picker.sourceType =
    picker.cameraDevice = .front
    picker.cameraCaptureMode = .photo
    picker.modalPresentationStyle = .fullScreen
    present(picker,animated: true,completion: nil)
    else {

    That’s it.
    This is the only code require to POST multipart request using the Alamofire 4.0 to a PHP Server.

    For the Backend we will write the script in PHP and connect it with MySQL.

    die(“Connection failed: ” . $conn->connect_error);
    $max_filesize = 10485760;
    $upload_path = ‘images/’;
    $description = $_POST[‘imgdesc’];
    $filename = $_FILES[‘userfile’][‘name’];
    $ext = substr($filename, strpos($filename,’.’), strlen($filename)-1);
    if(filesize($_FILES[‘userfile’][‘tmp_name’]) > $max_filesize)
    die(‘The file you attempted to upload is too large.’);
    die(‘You cannot upload to the specified directory, please CHMOD it to 777.’);
    if(move_uploaded_file($_FILES[‘userfile’][‘tmp_name’],$upload_path . $filename))
    $query = “INSERT INTO test_table (image, name) VALUES (‘$filename’, ‘$description’)”;
    if ($conn->query($query) === TRUE) {
    echo “{‘msg’:’New record created successfully’}”;
    } else {
    echo “{‘Error’: ‘” . $query . “
    ’}” . $conn->error;
    else {
    echo ‘{“ss”:”There was an error during the file upload. Please try again.”}’;


    PS: Just change the "hostname", "username", "password", "dbname" accordingly to yours.
    I have just put it for your reference. 
    Also you need to change the name of the table in the sql statement accordingly.
    $query = "INSERT INTO test_table (image, name) VALUES ('$filename', '$description')";

    You can download the whole source code of Swift for the same from my GitHub repository.

    Image Source: InterTrust

Load More By qwertyasvishwa
Load More In code corner

Check Also

Interaction with UITextField, UIButton, UILabel

Here, this article gives the information about some of the components of Xcode, which are …