One of the coolest things an intermediate programmer can dabble with is interfacing their program with a server. It’s something that I’ve wanted to do for years, and up until recently I haven’t had the skills to do it. I am currently in the process of re-vamping selfie swap, and I need to store images on my server that are taken in the app. This is quite easy to do.

For the purposes of this tutorial, I am going to skip how to use UIImagePickers to get an image from the iPhone’s camera. This works with an image. First, here is the client side code:

 

NSString *urlString = @"http://www.example.com/path/to/script.php";

    //Convert your UIImage to NSDate
    NSData *imageData = UIImageJPEGRepresentation(yourImage,.3);     

    if (imageData != nil)
    {
        NSString *filenames = [NSString stringWithFormat:@"SelfieName"];      //set name here

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:urlString]];
        [request setHTTPMethod:@"POST"];

        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

        NSMutableData *body = [NSMutableData data];

        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"filenames\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[filenames dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//I use a method called randomStringWithLength: to create a unique name for the file, so when all the aapps are sending files to the server, none of them will have the same name:
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n",[self randomStringWithLength:10]] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[NSData dataWithData:imageData]];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

        [request setHTTPBody:body];

        NSOperationQueue *queue = [[NSOperationQueue alloc] init];

        //I chose to run my code async so the app could continue doing stuff while the image was sent to the server.
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
        {

            NSData *returnData = data;
            NSLog(@"data recieved!");

            //Do what you want with your return data. 

        }];
NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

-(NSString *) randomStringWithLength: (int) len {
 
 NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
 
 for (int i=0; i<len; i++) {
 [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform([letters length]) % [letters length]]];
 }
 
 return randomString;
}

This code  can be implemented almost anywhere in your existing code. Change the url name to your script and you’re almost there! Speaking of scripts…


<?php

$target_path = "imageDump/";  //where you want the uploaded images to go, I recommend an upload only directory
$target_path = $target_path . basename( $_FILES['userfile']['name'] );

if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_path)) {

//successful move
} else {

//unsuccessful move
}
?>

 

And there you go! Hoopefully you found this usefull.

-Jonathan Malott

4 Comments

  • Ali Haidar says:

    THANK YOU DUDE !!! YOU ARE MY HERO !
    ive been looking all over the internet for a tutorial, everything i found out there kept giving me errors !! Your code was perfect though !! worked from the first time !!
    Thank you !!

  • Rohant says:

    Hello Jonathan,

    Great tutorial! But do you have an example, where you have WCF REST services?
    -Regards,
    Rohant K

  • KD says:

    I am also looking for the same problem. I have to create an app, which will auto capture the Image and immidiately send to remote PC (through TCP over Wifi), this process will go continue for long time. In your case you are uploading images to server, I can also use this.
    Can you provide full code, which will be helpful for creating simple app.

Submit a Comment.