• Satya Brata

    keep it brother you are my inspiration for iOS development, thanks a lot.

  • Dan Florio

    Thank you for the tutorial, but I’m having an issue. I’ve created an xCode file, created the UI, and copy+pasted your swift code to the View Controller. Everything looks fine with no errors. I then created a PHP file on my local server called file_upload.php, and copied the PHP code you provided. In the View Controller swift file, I set

    myUrl = NSURL(string: “http://localhost/file_upload.php”);

    I am able to run the app, choose an image from the image picker, and push “upload”. After about a minute, I get the following response:

    ****** response data =

    Notice: Undefined index: firstName in /var/www/html/file_upload.php on line 3
    Notice: Undefined index: lastName in /var/www/html/file_upload.php on line 4
    Notice: Undefined index: userId in /var/www/html/file_upload.php on line 5
    Notice: Undefined index: file in /var/www/html/file_upload.php on line 12
    Notice: Undefined index: file in /var/www/html/file_upload.php on line 14
    Notice: Undefined index: userId in /var/www/html/file_upload.php on line 24

    {“Message”:”Sorry, there was an error uploading your file.”,”Status”:”Error”,”userId”:null}

    I have no idea why this is happening, as all of those variables are set in the swift code you provided. Am I doing something wrong?

    Thanks again!

    • @danflorio:disqus thank you for your comment. Please make sure that names of parameters you send are correct and they are actually being sent… Also make sure in PHP you read them with the same names as they are sent.

      Also in your PHP code can you change $_POST to $_REQUEST

      For example:
      $firstName = $_REQUEST[“firstName”];
      $lastName = $_REQUEST[“lastName”];
      $userId = $_REQUEST[“userId”];

      when you specify parameter name, please make sure the quotes are straight “” and not “ ”
      and then print out all of them to see they are coming. For example:

      echo $firstName;
      echo $lastName;
      echo $userId;

      to test that your PHP scripts reads parameters correctly just access it via the web browser. For example: Open your web browser using this URL:

      http://localhost/file_upload.php?firstName=Dan&lastName=Florio&userId=9

      will it print parameters correctly?

      • Dan Florio

        Thanks for the quick response. As far as I can tell, the parameters match in the swift file and PHP file. Here are the first few lines of myImageUploadRequest in the swift file:
        ——————begin swift excerpt——————-
        func myImageUploadRequest()
        {
        let myUrl = NSURL(string: “http://localhost/file_upload.php”);
        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = “POST”;

        let param = [
        “firstName” : “Dan”,
        “lastName” : “Florio”,
        “userId” : “9”
        ]

        let boundary = generateBoundaryString()
        request.setValue(“multipart/form-data; boundary=(boundary)”, forHTTPHeaderField: “Content-Type”)
        let imageData = UIImageJPEGRepresentation(myImageView.image, 1)
        if(imageData==nil) { return; }

        request.HTTPBody = createBodyWithParameters(param, filePathKey: “file”, imageDataKey: imageData, boundary: boundary)
        ——————end swift excerpt——————-

        And the parameter declarations in the PHP file:
        ——————begin PHP excerpt——————-

        $firstName = $_REQUEST[“firstName”];
        $lastName = $_REQUEST[“lastName”];
        $userId = $_REQUEST[“userId”];
        $target_dir = “uploads/”;
        ——————end PHP excerpt——————-

        I get the same error message in xCode whether I’m using POST or REQUEST.

        The test you mentioned works, however. After changing POST to REQUEST, and adding the echo statements, I can navigate to:
        http://localhost/file_upload.php?firstName=dan&lastName=florio&userId=9

        and receive the following output:
        danflorio9
        Notice: Undefined index: file in /var/www/localhost/file_upload.php on line 17
        Notice: Undefined index: file in /var/www/localhost/file_upload.php on line 19
        {“Message”:”Sorry, there was an error uploading your file.”,”Status”:”Error”,”userId”:”9″}

        I’ll continue to sift through the code to check for any mis-matched variables, but please let me know if you have any other suggestions.

      • Dan Florio

        I’ve managed to get the app working by retyping the code from scratch while following your video. Looks like something went wrong when I copy+pasted the code in this blog post. I’ll try to investigate to figure out what’s different and let you know, just incase others have the same issue!

        EDIT: I found the problem. It has to do with the dashes used when setting the boundaries. Will post the solution in a new comment for anyone else having the same problem.

        Thanks again.
        PS: I’m hoping to be able to upload an audio file instead of an image file. I’m assuming I can accomplish that by tweaking this code, but do you have any specific suggestions?

        • Are you sure is boundary? I have check and even retype my boundary function, but still get the same error “undefined index”

    • Guest

      For anyone who copy+pastes this code, be aware of a few changes that need to be made:

      1. The font on this blog uses stylized quotes ( “ ″ ) instead of ” “, so make sure to replace all of those in the code (a search and replace gets this done quickly)

      2. For the section of code where you set the boundary…

      body.appendString(“–(boundary)rn”)

      body.appendString(“Content-Disposition: form-data; name=”(filePathKey!)”; filename=”(filename)”rn”)
      body.appendString(“Content-Type: (mimetype)rnrn”)
      body.appendData(imageDataKey)
      body.appendString(“rn”)

      body.appendString(“–(boundary)–rn”)

      …those dashes are supposed to be two dashes next to each other ( — ). The blog auto-formats two dashes to one large dash ( – ), so make sure to replace those as well (that one took me a while!).

      Hope this helps someone!

  • Dan Florio

    For those who copy+paste the swift code, be aware of a few changes that need to be made:

    1. The font on this blog uses stylized quotes ( “ ″ ) instead of ” “, so make sure to replace all of those in the code (a search and replace gets this done quickly)

    2. For the section of code where you set the boundary…

    body.appendString(“–(boundary)rn”)

    body.appendString(“Content-Disposition: form-data; name=”(filePathKey!)”; filename=”(filename)”rn”)
    body.appendString(“Content-Type: (mimetype)rnrn”)
    body.appendData(imageDataKey)
    body.appendString(“rn”)

    body.appendString(“–(boundary)–rn”)

    …those dashes are supposed to be two dashes next to each other ( — ). The blog auto-formats two dashes to one large dash ( – ), so make sure to replace those as well (that one took me a while!).

    Hope this helps someone!

    • @danflorio:disqus Awesome! Thank you Dan!
      I will make changes to my blog to make it format quotes and dashes properly.

      • Miroslav Mickey Lazarevic

        Well format quotes and dashes are still wrong on the blog 🙁 I lost to much time until got it to work but nvm at least code is working…

    • Miroslav Mickey Lazarevic

      Thank you! You saved my day…

  • karin khera

    Hey Kargo

    Your tutorial was very helpful. I was able to upload a image to the server. How ever, I am having trouble in parsing the JSON data that is coming from the server. I used your way of parsing and also tried a another method which was SwiftyJson. What ever method i use, i still get a error. Its look like the json variable is always nil. could you please help me out?

    Thanks

    • @karinkhera:disqus in your app, are you able to print raw response that arrived from server script? does it contain valid json?

      • karin khera

        Yes I am able to. This is the result:

        ****** response data = post method{“Message”:”The file player-snap.jpg has been uploaded.”,”Status”:”OK”,”userId”:”45637″}

        • @karinkhera:disqus why do you have “post method” in front of json string. Is it part of response message?

          • karin khera

            No that should have been there. I was echoing some text in the php file, which i shouldn’t have. Everything is taken out and the JSON is now working.

            Thanks

          • @karinkhera:disqus awesome! So I guess the problem is solved now? 🙂

  • crewfly

    Hi kargopolov,

    Was wondering, your uploader limits the image file type to JPG. How can you allow for PNG or allow both wherein a user can either use the Camera or the Photo library to upload image to server?
    Thanks. This code sample is great. Had a few trial and errors to get it working as the copy+paste from the your code sample generates a lot of type errors once in xCode. Got it going, but would like to expand it to PNG as well or allow both files from a single code.

    • Yes, my blog uses stylized quotes ( “ ″ ) instead of ” ” and you need to replace them if copy+paste. I agree this is frustrating :(… As to your question, I believe iPhone stores photos taken with device camera as JPGs. Are you looking for ways to convert existing photos from JPG to PNG and then send PNG to server? or you simply need an example on how to use UIImagePickerControllerSourceType.Camera instead of UIImagePickerControllerSourceType.PhotoLibrary?

  • Hapit Hidayat

    Hi kargopolov, i’ve tested your solution and I have some problem in the uploading part (the error message “Sorry, there was an error uploading your file” keeps appearing). Do you mind sharing your thoughts on my code below?
    http://pastebin.com/RY16RTvK , my code php http://pastebin.com/zBxDWppc

    Thanks

  • raimonds

    Hello Kargopolov, i have a problem with my code. I wrote all exactly as you wrote, but i have such an error when uploading image.

    ****** response data =

    Notice: Undefined index: userId in /home/raimonds/script.php on line 36

    {“Message”:”First name field empty”,”Status”:”Error”,”userId”:null}

  • Alimwa

    Hi Kargopolov

    Thanks for your tutoriel. I m looking how to upload multiple images from my iOS App to thé server. The images are in Bundle directory.

  • nathan Hunsberger

    Hi, I followed all of this, and had to retype it all from watching videos. The php I had to correct by running the code and checking the error message. I’d like to say THANKS for the code, but I do get a problem. I tried checking for parameters, yet they don’t show, I followed the comments below to check for parameters. I ran the code in a web browser and no parameters show up, even after updating the url to add in parameters. I also tried to check for parameters in the app, and got nothing. I also found that the app returns no errors, but in the log, the ****** Response Data returns nothing. It says ***** Response Data = . Please help!!!!!!!!

    • Hi Nathan, it is difficult to say. What I would try:
      1. Print out parameters like this to make sure there are no typos in parameter names: echo $_REQUEST[“userId”]

      2. For the time being I would set permissions on the folder I am uploading an image to 777 using: chmod 777 completePathToYourFolderHere…

      Let me know what would be the result…

  • josue sanchez

    Hi kargopolov,

    Thanks for the video, just gives me an error, if it’s not my server, was on the line “echo json_encode ([….” change the square brackets by “array (…” and then not me fails but not if it affects so do not increase it, as I do not get the parameters of the POST.

    Another question is how can I do to upload multiple images, and enter the “photo library” and be able to select and upload multiple images simultaneously.

    Thanks for the help.

    • Jose, I am sorry. May I ask you to rephrase your second question? I do not understand it.. Regarding the Upload Multiple Images example, I do not have it at the moment. I might work on it one day soon but at this moment here is a list of upcoming videos: http://swiftdeveloperblog.com/upcoming-videos/

  • Tattat Leong

    think you i solve problems
    Hi Sir

    can i use the xampp for the testing?

    the URL is..
    let myUrl = NSURL(string: “http://127.0.0.1/swiftjson/http-post-example-script.php”);
    // let myUrl = NSURL(string: “http://www.swiftdeveloperblog.com/http-post-example-script/”);
    let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = “POST”;

    erro is..

    ******* response = { URL: http://127.0.0.1/swiftjson/http-post-example-script.php } { status code: 200, headers {

    Connection = “Keep-Alive”;

    “Content-Length” = 1037;

    “Content-Type” = “text/html; charset=UTF-8”;

    Date = “Mon, 13 Jul 2015 18:54:39 GMT”;

    “Keep-Alive” = “timeout=5, max=100”;

    Server = “Apache/2.4.12 (Unix) OpenSSL/1.0.1m PHP/5.6.8 mod_perl/2.0.8-dev Perl/v5.16.3”;

    “X-Powered-By” = “PHP/5.6.8”;

    } }

    ****** response data =

    Notice: Undefined index: firstName in /Applications/XAMPP/xamppfiles/htdocs/swiftjson/http-post-example-script.php on line 4

    Notice: Undefined index: lastName in /Applications/XAMPP/xamppfiles/htdocs/swiftjson/http-post-example-script.php on line 5

    Notice: Undefined index: userId in /Applications/XAMPP/xamppfiles/htdocs/swiftjson/http-post-example-script.php on line 6

    Notice: Undefined index: file in /Applications/XAMPP/xamppfiles/htdocs/swiftjson/http-post-example-script.php on line 15

    Notice: Undefined index: file in /Applications/XAMPP/xamppfiles/htdocs/swiftjson/http-post-example-script.php on line 17

    Notice: Undefined index: userId in /Applications/XAMPP/xamppfiles/htdocs/swiftjson/http-post-example-script.php on line 29

    {“Message”:”Sorry, there was an error uploading your file.”,”Status”:”Error”,”userId”:null}

  • Gui Kunzler

    Hi Kargopolov,

    I am getting the following response.

    ******* response = { URL: http://localhost/SwiftAppAndMYSQL/scripts/imageUpload.php } { status code: 200, headers {

    Connection = “Keep-Alive”;

    “Content-Length” = 86;

    “Content-Type” = “text/html”;

    Date = “Thu, 23 Jul 2015 09:26:06 GMT”;

    “Keep-Alive” = “timeout=5, max=98”;

    Server = “Apache/2.4.12 (Unix) OpenSSL/1.0.1m PHP/5.5.24 mod_perl/2.0.8-dev Perl/v5.16.3”;

    “X-Powered-By” = “PHP/5.5.24”;

    } }

    ****** response data = {“message”:”The file user-profile.jpg has been uploaded.”,”status”:”OK”,”userId”:”19″}

    ****** json = Optional({

    message = “The file user-profile.jpg has been uploaded.”;

    status = OK;

    userId = 19;

    })

    The php script is able to create the folder, BUT any folder it creates is always empty. I imagine the script should be able to create images inside the folders right?

  • Sergey your the man, your Swift tutorials has helped someone like me with a PHP background to develop on mobile platform. Thank you 🙂

  • How can I support PNG file as well?

    • Farhard, sorry for this short reply.. To upload PNG images you can use UIImagePNGRepresentation instead of UIImageJPEGRepresentation in Swift.

      • I thought that would be the problem, but I result in error from the PHP server side when I take picture with a camera. If I use saved photo from the Internet the image get uploaded.

        Here is the Error:
        fopen(tmp/photos/a9cebef5be936e14c53dda8ad656a68d.jpg): failed to open stream: No such file or directory in /var/www/html/App/image-upload.php

        As you can see I upload it into temp folder before uploading it to server. I believe the data of image is not being send to server if is taken with Camera for some reason.

        UPDATE: Actually I can’t send any image taken by Camera, even if i save it to gallery.

  • Kashish

    How would you do OAUTH? I have an API which provides api key that we need to add so the server knows which info to access, thanks 🙂

  • Oliver Gerez

    Hello, I tried this example and I’m unable to run it properly in XCode 7.

    At first I got an error “App Transport Security has blocked a cleartext HTTP resource load since it’s insecure.
    I edited the info.plist to allow insecure connections:
    -key NSAppTransportSecurity Dictionary—> key NSAllowsArbitraryLoads Boolean: YES
    this allows me to use other services (for example SOAP services work fine)

    However, now I’m getting an error 1001 “The request timed out”. I know the server is up and running, and the service works.
    Is there another key I need? do you have any idea why it sends me this error?

  • josue sanchez

    Hello, I would like you to give me an idea of how to solve the problem of upload images, as with the swift change 2.x, I can not upload the image

    • Do you get an error message? What is it?

      • josue sanchez

        Hello, it shows no mistake, I was watching that certain weight simply do not load up the image on the server.

        There is no way that the images that are loaded from the camera or other heavier load equally.

        how I can compress?

        • I doubt it is because of an image size but you can try uploading a lower quality image. For example extract JPEG image of quality 0.5 instead of 1:
          let imageData = UIImageJPEGRepresentation(myImageView.image, 0.5)

          • josue sanchez

            if it worked thank you!

  • talha

    please can you tell how to make a user multi picture upload only 4 pictures and how i can make seperate ids and send pictures to seperate users profiles

  • António Montrond

    HI, it is not work for me. please can i have a little hand.

    my codes

    func myImageUploadRequest()

    {

    let myUrl = NSURL(string: “http://127.0.0.1/imagens/ImageUpload.php”);

    let request = NSMutableURLRequest(URL:myUrl!)

    request.HTTPMethod = “POST”;

    let param = [

    “firstName” : “Sergey”,

    “lastName” : “Kargopolov”,

    “userId” : “9”

    ]

    let boundary = generateBoundaryString()

    request.setValue(“multipart/form-data; boundary=(boundary)”, forHTTPHeaderField: “Content-Type”)

    let imageData = UIImageJPEGRepresentation(myImageView.image!, 1)

    if(imageData==nil) { return; }

    request.HTTPBody = createBodyWithParameters(param, filePathKey: “file”, imageDataKey: imageData!, boundary: boundary)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {

    data, response, error in

    if error != nil {

    print(“error=(error)”)

    return

    }

    // You can print out response object

    print(“******* response = (response)”)

    // Print out reponse body

    let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

    print(“****** response data = (responseString!)”)

    do {

    var json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

    } catch let error as NSError{

    }

    dispatch_async(dispatch_get_main_queue(),{

    self.myImageView.image = nil;

    });

    /*

    if let parseJSON = json {

    var firstNameValue = parseJSON[“firstName”] as? String

    println(“firstNameValue: (firstNameValue)”)

    }

    */

    }

    task.resume()

    }

    func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {

    let body = NSMutableData();

    if parameters != nil {

    for (key, value) in parameters! {

    body.appendString(“–(boundary)rn”)

    body.appendString(“Content-Disposition: form-data; name=”(key)”rnrn”)

    body.appendString(“(value)rn”)

    }

    }

    let filename = “user-profile.jpg”

    let mimetype = “image/jpg”

    body.appendString(“–(boundary)rn”)

    body.appendString(“Content-Disposition: form-data; name=”(filePathKey!)”; filename=”(filename)”rn”)

    body.appendString(“Content-Type: (mimetype)rnrn”)

    body.appendData(imageDataKey)

    body.appendString(“rn”)

    body.appendString(“–(boundary)–rn”)

    return body

    }

    func generateBoundaryString() -> String {

    return “Boundary-(NSUUID().UUIDString)”

    }

    }

    extension NSMutableData {

    func appendString(string: String) {

    let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)

    appendData(data!)

    }

    }

  • Yacov

    Hey great post, concerning the http script that you talk in video 2. Do You mean this ?

    fetch_object())

    {

    // Add each row into our results array

    $tempArray = $row;

    array_push($resultArray, $tempArray);

    }

    // Finally, encode the array to JSON and output the results

    echo json_encode($resultArray);

    }

    // Close connections

    mysqli_close($con);

    ?>

  • Lokanath Nayak

    Hi kargopolov, I am new to XCODE, and getting the below attached error.. Could you please let me know if I am missing anything..?

    • Harish Kanakarajan

      Try to use this,

      func imagePickerController(picker: UIImagePickerController,

      didFinishPickingMediaWithInfo info: [String : AnyObject]){

      userImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage

      self.dismissViewControllerAnimated(true, completion: nil)

      }

    • Looks like the function signature is incorrect. Try using String:Object like so:

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

      • Lokanath Nayak

        Thanks Sir, THis worked me a lot..:)

  • Harish Kanakarajan

    Hello Kargopolov,

    I got some minor issues regarding the version and some where deprecated. And after fixing it. It worked like charm!! Thanks,

    But I am new to IOS and swift, can you please help me out how could I verify this in my local enviroment?

    • What would you like to verify on your local environment?

  • Lokanath Nayak

    My app runs well with ur code without any error. when when I upload the app here is what I get as an error:

    App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app’s Info.plist file.

    error=Optional(Error Domain=NSURLErrorDomain Code=-1022 “The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.” UserInfo={NSUnderlyingError=0x7fb54b071440 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 “(null)”}, NSErrorFailingURLStringKey=http://designsultima.com/iosapp/index.php, NSErrorFailingURLKey=http://designsultima.com/iosapp/index.php, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.})

    DOES SSL required to upload a file to server?

  • mxd0s

    Hi I get this error message when uploading a photo.

    Hope you can help me.

    ******* response = Optional( { URL: http://./uploadimage.php } { status code: 500, headers {
    Connection = close;
    “Content-Length” = 0;
    “Content-Type” = “text/html”;
    Date = “Thu, 12 Nov 2015 23:21:53 GMT”;
    Server = “Apache/2.2.31 (Unix)”;
    “X-Powered-By” = “PHP/5.3.29”;
    } })
    ****** response data = Error Domain=NSCocoaErrorDomain Code=3840 “No value.” UserInfo={NSDebugDescription=No value.}

    • 500 error means you have an error in your php script. There might be a typo for example. Can you check it line by line to see why it breaks?

      • Kenny W.

        First of all, thank you for taking the time to make this tutorial.

        But I am having a similar error (500) as the person above, I’ve literally copy and pasted the php code and changed the path to $target_dir = “./”;

        I’ve tried entering the php code into http://phpcodechecker.com/ and no errors. I’m lost

        Error Domain=NSCocoaErrorDomain Code=3840 “JSON text did not start with array or object and option to allow fragments not set.” UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

        • Kenny, it is better if the path to your images folder is absolute. Also, try creating the images folder manually, so that you do not need to create it with php code and uploading an image to this folder. Will it help?

          • Kenny W.

            I’ve tried that already, and that’s not the issue. It still gives the same error

          • Kenny, right after readying HTTP Parameters, can you echo $_POST object file details and see if it contains correct file details?

            for example:

            echo $_FILES[“file”][“name”];

            echo “”;

            echo $_FILES[“file”][“tmp_name”];

            return;
            and return after that, so that you do not get 500 error. Look into your Xcode console for return message from http request. You might not need to JSON parse it. or if you still want to parse json, then put this into array and then convert to JSON:

            echo json_encode( { “file_name”: $_FILES[“file”][“name”] } );

          • Kenny W.

            I’ve managed to get it working after looking at other similar code online and simplified it without using parameters. Thank you

            However, I still get a strange error code 200 and this

            ****** response data =

            Error Domain=NSCocoaErrorDomain Code=3840 “No value.” UserInfo={NSDebugDescription=No value.}

            But the image uploads just fine. Weird.

            Here’s my swift and php code:

          • I think this is because your Swift code expects JSON response to arrive but PHP script does not send any. If the move was successful try adding this PHP script:

            echo json_encode(“{“messagee”:”OK”}”);
            return;

            or

            $my_response = array(‘message’=>’OK’);
            echo json_encoded($my_response);
            return;

          • Kenny W.

            You were right, it was the missing response php code. Everything is good now

            Thank you! 🙂

          • typo :)… Happy it worked now 🙂

  • jphly

    Hi. Thank you so much for your tutorials. Very helpful.

    I have been trying to get the image upload to work, but it’s not working for some reason. I get a 200 response from the php script, but I get the Error status, rather than OK. here is the response I’m getting:

    ******* response = Optional( { URL: http://…/add_art.php } { status code: 200, headers {

    Connection = close;

    “Content-Encoding” = gzip;

    “Content-Length” = 138;

    “Content-Type” = “text/html; charset=UTF-8”;

    Date = “Tue, 24 Nov 2015 00:47:32 GMT”;

    Server = “Apache/2.4.10 (Debian)”;

    Vary = “Accept-Encoding”;

    } })

    ****** response data = {“Message”:”Sorry, there was an error uploading your file: user-profile.jpg to directory: /var/www/html/images/user-profile.jpg”,”Status”:”Error”}

    {

    Message = “Sorry, there was an error uploading your file: user-profile.jpg to directory: /var/www/html/images/user-profile.jpg”;

    Status = Error;

    }

    I had to make some changes to the swift code to compile in Swift 2.0 and iOS9, but it seems to compile and run without error. I’m not sure how to debug this now.

    Thank you for any help you can offer.

    • jphly

      No worries – issue is resolved. I just had to adjust some of the settings in my php.ini file.

      • mario

        can you please tell me what settings did you adjust on your php.ini file?

        • jphly

          These are the settings that I changed from the default:
          max_execution_time = 60
          max_input_time = 60
          post_max_size = 20M
          upload_max_filesize = 10M

          Hope that helps.

  • Jake Roland

    Hey Kargopolov,

    I followed your tutorial and I got some errors. It has to do with me using xcode 7.1 and swift 2. when I want connect to server part by used swift2. My biggest concern is when i do body.appendString it said “value of NSMutable has no member appendString”

    • try this approach:

      do {

      let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

      // YOUR OTHER CODE HERE

      } catch()
      {
      print(error)
      }

    • Sriram Vepuri

      Jake,

      How did you resolve the error message with body.appendString?

  • Sriram Vepuri

    Hi Kargopolov,

    I am trying to run the code and I get this error message “Value of type NSMutableData has no member appendString” wherever we have body.appendString commands in the createBodyWithParameters function. Do you have an idea on how to resolve this? The regular string concatenation operators like + and += aren’t working for appending strings to NSMutableData. Please advise.

  • Sriram Vepuri

    Hi Kargopolov,

    Thanks for the tutorial. While trying to upload the image, I encountered an error. I tried to see that using this command $_FILES[“file”][“error”]: 1. The error message is “The data couldn’t be read because it isn’t in the correct format.” Please advise me on how to resolve this issue.

    I am able to print parameters using the PHP script. So the POST parameters are working. Perhaps the problem is only with the image. The value of $_FILES[“file”][“tmp_name”] is empty.

    Response object
    { status code: 200, headers {
    Connection = “Keep-Alive”;
    “Content-Length” = 121;
    “Content-Type” = “text/html”;
    Date = “Sun, 27 Dec 2015 04:24:39 GMT”;
    “Keep-Alive” = “timeout=5, max=100”;
    Server = “Apache/2.4.16 (Unix) PHP/5.5.29”;
    “X-Powered-By” = “PHP/5.5.29”;
    } })

    ****** response data =
    {“Message”:”Sorry, there was an error uploading your file.”,”Status”:”Error”}

    • Sriram, I would do two things first. 1) Just before sending an HTTP Request check the length of Image data object to make sure it is not empty. 2) Double check the names of HTTP Request parameters I am sending and reading to make sure there are no typos. For image profile_image and profile_Image are different key names. One of them has capital “I” while another has lower case “i”…

      • Sriram Vepuri

        Kargopolov, I have checked the length of image object before the request.HTTPBody statement and also in the
        createBodyWithParameters function. The image size is around 3 MB. Regarding your second point, I am able to verify the value of the file name in the php script using the command $_FILES[“file”][“name”]. The value is user-profile.jpg. However, as mentioned earlier, I have trouble reading the content from $_FILES[“file”][“tmp_name”]. It has an empty value.

        I tweaked your Swift code as these two lines are causing an error – Extra argument ‘error’ in call.

        var err: NSError?
        var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary

        To fix this error, I have used the solution offered in this link at StackOverflow
        http://stackoverflow.com/questions/31073497/swift-extra-argument-error-in-call/31073812#31073812

        The tweaked component looks like this. Do you think this has anything to do with the upload error?

        do {
        if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
        print(jsonResult) }
        } catch let error as NSError {
        print(error.localizedDescription)
        }

    • Sriram, can you make sure that the error message “The data couldn’t be read because it isn’t in the correct format.” is indeed from $_FILES[“file”][“error”]? also, have a look at this discussion:

      http://stackoverflow.com/questions/14472741/files-field-tmp-name-has-no-value-on-jpg-file-extension

      • Sriram Vepuri

        Kargopolov, Thanks for your support. I have fixed the issue. There were two problems.
        1) My php.ini file was named php.ini.default. Changing the parameters upload_max_filesize and post_max_size didn’t yield any result, until I renamed the file to php.ini
        2) After the file name issue, I encountered a challenge with the permissions to the folder in which the uploaded image has to be moved. I have changed the permissions and was able to see the image uploaded in to the folder.
        I sincerely appreciate your help. Thank you so much 🙂

      • Sriram Vepuri

        Kargopolov, I have documented my observations in StackOveflow. Here is the link. http://stackoverflow.com/a/34505700/3681985

  • Freddie Tibbles

    Hi Kargopolov,

    Firstly, thank you very much for the time you have taken to make and maintain these tutorials. Your a hero!

    Secondly, i am having issues with my submission of an image. Basically the image submission appears to be completely empty! I have th exact same code as the example, including updates explained in the comments here. So i am somewhat lost as to what is causing it! I am new to Swift/XCode, but have extensive experience in front end web development.

    For clarity, i can submit user information from within the app into a local DB i have setup, its just the image upload that is not working.

    Any advice would be HUGELY appreciated! 🙂

    “`

    func myImageUploadRequest() {

    let myUrl = NSURL(string: “http://jaak.reg/imageUpload.php”)

    let request = NSMutableURLRequest(URL: myUrl!)

    request.HTTPMethod = “POST”

    let param = [

    “firstName”: “Bob”,

    “lastName”: “jere”,

    “userId”: “9”

    ]

    let boundary = generateBoundaryString()

    request.setValue(“multiplart/form-data; boundary=(boundary)”, forHTTPHeaderField: “Content-Type”)

    let imageData = UIImageJPEGRepresentation(imageView.image!, 0.5)

    if imageData == nil {

    return print(“No image”)

    }

    request.HTTPBody = createBodyWithParameters(param, filePathKey: “newfile”, imageDataKey: imageData!, boundary: boundary)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {

    data, response, error in

    if error != nil {

    print(“error=(error)”)

    }

    do {

    if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {

    print(jsonResult)

    }

    } catch let error as NSError {

    print(error.localizedDescription)

    }

    }

    task.resume()

    }

    “`

    Thanks,

  • Freddie Tibbles

    Hi Kargopolov,

    Firstly, thank you very much for the time you have taken to make and maintain these tutorials. Your a hero!

    Secondly, i am having issues with my submission of an image. Basically the image submission appears to be completely empty! I have th exact same code as the example, including updates explained in the comments here. So i am somewhat lost as to what is causing it! I am new to Swift/XCode, but have extensive experience in front end web development.

    For clarity, i can submit user information from within the app into a local DB i have setup, its just the image upload that is not working.

    Any advice would be HUGELY appreciated! 🙂

    “`

    func myImageUploadRequest() {

    let myUrl = NSURL(string: “http://jaak.reg/imageUpload.php”)

    let request = NSMutableURLRequest(URL: myUrl!)

    request.HTTPMethod = “POST”

    let param = [

    “firstName”: “Bob”,

    “lastName”: “jere”,

    “userId”: “9”

    ]

    let boundary = generateBoundaryString()

    request.setValue(“multiplart/form-data; boundary=(boundary)”, forHTTPHeaderField: “Content-Type”)

    let imageData = UIImageJPEGRepresentation(imageView.image!, 0.5)

    if imageData == nil {

    return print(“No image”)

    }

    request.HTTPBody = createBodyWithParameters(param, filePathKey: “newfile”, imageDataKey: imageData!, boundary: boundary)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {

    data, response, error in

    if error != nil {

    print(“error=(error)”)

    }

    do {

    if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {

    print(jsonResult)

    }

    } catch let error as NSError {

    print(error.localizedDescription)

    }

    }

    task.resume()

    }

    “`

    Thanks,

  • Ridd Lore

    Your code does not seem to run, but great info.

    • 🙂 thank you :). What exactly does not work?

  • Vivek Rajagopal

    Hello Mr.Kargopolov,

    Great to meet you through this discussion.
    Your tutorials are very impressive and helped me achieve 2 successful projects.
    I’m currently working on a simple face distortion app using Swift 2.

    I wrote the code for displaying the face camera and detect the face.
    I need to animate the eyes with a CIBumpDistortion effect.

    Please help me to code.

    Looking forward for your help Sir.

    Thanks,
    Vivek.

    • Hi Vivek! I never worked with CIBumpDistortion and do not have any example to share with you.

  • Greg Hanley

    Hello!

    Once again – fantastic, intuitive tutorial, took plenty from it!

    I am hosting my PHP page on the following URL (Web Server from University):

    let myUrl = NSURL(string: “http://<<>>/greghanley3/ReelTime/imageUpload.php”);

    I have created a folder in the following directory, on this web server:

    /home/hg/images

    In my PHP file (imageUpload.php), I am using the following:

    $target_dir = “/home/hg/images”;if(!file_exists($target_dir))
    {
    mkdir($target_dir, 0777, true);
    }

    However, I am getting an issue when attempting to upload the file to this web structure of files:

    First of all, this is what is first printed in the XCode console, upon attempting to upload the image:

    ******* response = Optional( { URL: http://<<>>/greghanley3/ReelTime/imageUpload.php } { status code: 200, headers {

    Connection = “Keep-Alive”;

    “Content-Length” = 3665;

    “Content-Type” = “text/html”;

    Date = “Thu, 11 Feb 2016 15:52:34 GMT”;

    “Keep-Alive” = “timeout=15, max=100”;

    Server = Apache;

    “X-Powered-By” = “PHP/5.5.24-pl0-gentoo”;

    } })

    Then, the following appears:

    ****** response data =

    ( ! ) Warning: move_uploaded_file(/home/hg/images/user-profile.jpg): failed to open stream: Permission denied in /home/hg/public_html/ReelTime/imageUpload.php on line 14

    Call Stack

    #TimeMemoryFunctionLocation

    Lastly, the following appears in the XCode console:

    {“Message”:”Sorry, there was an error uploading your file.”,”Status”:”Error”,”userId”:”12459218″}

    Error Domain=NSCocoaErrorDomain Code=3840 “JSON text did not start with array or object and option to allow fragments not set.” UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

    NOTE: This “JSON text did not start with array or object” error was also given to me from your other tutorial, for writing user information from App -> PHP -> MySQL, although the data itself still wrote to the database, even when this popped up in the console, so I don’t think that is the issue here!

    Is it purely a permissions error on the Universities side form the setup of the web server?? To access this file system, I must provide a username + password, which is probably blocking any writing of images to the file structure here. Is that a reasonable conclusion to make? If so, should I take it up with the university to alter permissions in my favour in this case?

    Thanks once again Mr. Kargopolov, outstanding tutorials!

  • Greg Hanley

    Hello,

    Once again – a brilliant and extremely helpful tutorial! Really beneficial and suited to my needs!

    One thing, my files are saving without and issue at all, in my folder structure on my Web Server, but, I would also like to save a thumbnail version of each uploaded image (so that I can display the users upload in an “Instagram-Style” table layout in the app, i.e:

    [image] [image] [image]
    [image] [image] [image]
    [image] [image] [image]

    As a result, I would like each upload to be saved as a thumbnail also, upon writing to the server. I have read that PHP has a built-in “thumb” function, but is there anyway you can provide some help here for code in the PHP file to do this? Also, I am creating a folder for each user based on their unique ID, where there photos are uploaded to. As a result, would something like the following be the best design for the directory:

    (“currently how it looks”):

    “/ReelTime/images/{– USER ID HERE}/– USER ID + CURRENT TIMESTAMP.jpg”

    (“How I would like the thumbnails to be stored”):

    “/ReelTime/images/{– USER ID HERE}/thumbs/”thumb + — USER ID + CURRENT TIMESTAMP.jpg”

    Thought it would be interesting to see, and possible of interest to many people viewing this tutorial! Thanks once again, keep up the great work! 🙂

    Regards,
    Greg.

  • 陈佳禾

    I have copy your code, however,the problem is that I find that if I use the url of yours, it works, however, If i copy the php code to my own server, that does not work. And it comes with the error:

    ******* response = Optional( { URL: http://hanslen.me/php/postImage.php } { status code: 200, headers {

    Connection = “Keep-Alive”;

    “Content-Length” = 89;

    “Content-Type” = “text/html; charset=UTF-8”;

    Date = “Sat, 27 Feb 2016 23:18:55 GMT”;

    “Keep-Alive” = “timeout=5, max=100”;

    Server = “Apache/2.4.16 (Amazon) PHP/5.6.17”;

    “X-Powered-By” = “PHP/5.6.17”;

    } })

    ****** response data = {“Message”:”Sorry, there was an error uploading your file.”,”Status”:”Error”,”userId”:””}

    {

    Message = “Sorry, there was an error uploading your file.”;

    Status = Error;

    userId = “”;

    }
    I really need you help!!!

  • JD PARK

    Thank you very much.

  • marie Claire

    hi thanks for this tutorial ..i’m new at using swift and i want tio create a registration form,where i can add firstname ,lastname and the user’s photo dynamically .all this data should be added in the database using a php file .can you help me?

  • Adarsa Hebbar

    Hi sir,
    how to upload audio file to the php server using swift?
    I am using swift 1.3

    • Adarsa, you can use same approach to upload sound file to your server. I should have also added a check for file type/extention in my php script to check which kind of file is being uploaded.

  • Shamilla Selamat

    Thank you Sergey! YOU ARE AWESOME!

  • Ayoub Ghaddab

    Thank you so much, worked perfectly

  • Naveed Ahmed

    Thanks for an amazing tutorial. Can you please create the same tutorial with Alamofire?

  • Muneeb

    Can you please do this with FTP server??

  • Nisaa Roberts

    Does anyone know how I would write the string for php file that is stored locally? So instead of this
    let myUrl = NSURL(string: http://www.swiftdeveloperblog.com/http-post-example-script/);

    I am using MAMP and my php file is stored in applications/MAMP/htdocs.
    Many thanks,

  • Alberto Mier

    Hi, i implement this code but i have a problem in this line:
    let imageData: NSData = UIImageJPEGRepresentation(myImageView.image!, 1)!

    fatal error: unexpectedly found nil while unwrapping an Optional value

    • Justin Cohen

      I’m having the same problem. Has anyone figured this out?

  • Alberto Mier

    And my image view don´t show the image tha i load

  • Ryan

    Hello thank you for sharing. I am new to this so please bear with me. I have a question about uploading images requirement. When we upload images, do we need to have three different sizes as per requirement by apple when they approve an app? Or this rule doesn’t apply in this case? Thanks.

  • Edmund Siah

    Hi Kargopolov,
    thanks for the tutorial, is there possibility to upload file into folder thats password protected?
    Edmund

  • chen James

    it’s great tutorial, but some code need to change in xcode V7.3.1 because the NSData access method is already change. I use the code and it won’t working util I modify the NSData access method and it is working for me in xcode V7.3.1 now.
    Thanks

    • Thank you Chen! I have updated Swift code to a newer version.

    • Also, check out my new page with many short Swift code examples. Most if them should be with a recent Swift version. http://swiftdeveloperblog.com/code-examples/

      • chen James

        Hi kargopolov,
        I got a problem after upload jpg file to my server, I have got the upload jpg file by WinSCP tools from my server and I cannot open it by any picture application, it seems the jpg file is broken. Could you kindly help me?

        Thanks

  • ThankGod ForHis Promise

    Hello Mr. Kargopolov

    First I must say, thank you for these wonderful tutorial. Please how can I pick up a text file (eg. .doc, .pdf) from the mobile files directory and upload it to my server. Thanks.

  • amazedbyYou

    Hi! Can you please help me with this? I get this error.

    ******* response = Optional( { URL: http://url.local/uploadProfilePic.php } { status code: 200, headers {
    Connection = “Keep-Alive”;
    “Content-Length” = 580;
    “Content-Type” = “text/html”;
    Date = “Sat, 22 Oct 2016 15:34:17 GMT”;
    “Keep-Alive” = “timeout=5, max=100”;
    Server = “Apache/2.4.12 (Unix) PHP/5.5.25 mod_wsgi/3.5 Python/2.7.9 OpenSSL/1.0.1j”;
    Vary = “Accept-Encoding”;
    “X-Powered-By” = “PHP/5.5.25”;
    } })
    ****** response data = Array
    (
    [userid] => 23
    )
    Array
    (
    [file] => Array
    (
    [name] => user-profile.jpg
    [type] =>
    [tmp_name] =>
    [error] => 1
    [size] => 0
    )

    )

    I’m currently using Xcode 8 and Swift 3. Thanks for the help.

  • Åmol Çhavhan

    Can we same code for FTP transfer?