NSURLConnection – A Simple example – Upload image to server using POST method.

By | November 13, 2014

Make sure you setup the server and have gone through this post before reading this article.

You can read more about NSURLConnection Class from here.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/index.html#//apple_ref/occ/instm/NSURLConnection/

Here In this article I am going to select an image from the gallery and upload to a server using

1. Synchronous method
2. Asynchronous method – different ways.

First you have to make an interface like the below screenshot.
5 buttons, 1 Imageview and a label.
Make sure you hook all the controls to their respective labels and corresponding functions.

Upload Image To server using NSURLConnection

Upload Image To server using NSURLConnection

Now to the code.

ViewController.h


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UINavigationControllerDelegate,
UIImagePickerControllerDelegate, NSURLConnectionDelegate>{

    IBOutlet UILabel *response;
    NSMutableData *_responseData;
    
}


@property (strong, nonatomic) IBOutlet UIImageView* imageView;

- (IBAction) pickImage:(id)sender;


@end

ViewController.m


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
{
    NSData *pngData;
    NSData *syncResData;
    NSMutableURLRequest *request;
    UIActivityIndicatorView *indicator;
    
    #define URL            @"http://localhost/UploadImage/Upload_Image.php"  // change this URL
    #define NO_CONNECTION  @"No Connection"
    #define NO_IMAGE      @"NO IMAGE SELECTED"
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    pngData = nil;
    [self initPB];
}

- (IBAction) pickImage:(id)sender{
    
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    [self presentViewController:pickerController animated:YES completion:nil];
}

#pragma mark -
#pragma mark UIImagePickerControllerDelegate

- (void) imagePickerController:(UIImagePickerController *)picker
         didFinishPickingImage:(UIImage *)image
                   editingInfo:(NSDictionary *)editingInfo
{
    self.imageView.image = image;
    pngData = UIImagePNGRepresentation(image);
    [self dismissModalViewControllerAnimated:YES];
}

-(BOOL) setParams{
    
    if(pngData != nil){
        
        [indicator startAnimating];
        
        request = [NSMutableURLRequest new];
        request.timeoutInterval = 20.0;
        [request setURL:[NSURL URLWithString:URL]];
        [request setHTTPMethod:@"POST"];
        
        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
        [request setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
        [request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.26.14 (KHTML, like Gecko) Version/6.0.1 Safari/536.26.14" forHTTPHeaderField:@"User-Agent"];
        
        NSMutableData *body = [NSMutableData data];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploaded_file\"; filename=\"%@.png\"\r\n", @"Uploaded_file"] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        
        [body appendData:[NSData dataWithData:pngData]];
        
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        
        
        [request setHTTPBody:body];
        [request addValue:[NSString stringWithFormat:@"%d", [body length]] forHTTPHeaderField:@"Content-Length"];
        
        return TRUE;
        
    }else{
        
        response.text = NO_IMAGE;
     
        return FALSE;
    }
}

- (IBAction) uploadImageSync:(id)sender
{
    
    if( [self setParams]){
        
        NSError *error = nil;
        NSURLResponse *responseStr = nil;
        syncResData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseStr error:&error];
        NSString *returnString = [[NSString alloc] initWithData:syncResData encoding:NSUTF8StringEncoding];
        
        NSLog(@"ERROR %@", error);
        NSLog(@"RES %@", responseStr);
        
        NSLog(@"%@", returnString);
        
        if(error == nil){
            response.text = returnString;
        }
    
        [indicator stopAnimating];
    
    }
    
}

- (IBAction) uploadImageAsync1:(id)sender
{

     if( [self setParams]){
    
        NSOperationQueue *queue = [[NSOperationQueue alloc]init];
        
        // Loads the data for a URL request and executes a handler block on an operation queue when the request completes or fails.
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:queue
                               completionHandler:^(NSURLResponse *urlResponse, NSData *data, NSError *error){
                                   NSLog(@"Completed");
                                   
                                   response.text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   
                                   [indicator stopAnimating];
                                   [UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
                                   
                                   if (error) {
                                       NSLog(@"error:%@", error.localizedDescription);
                                   }
                                  
                               }];
     }
    

}

- (IBAction) uploadImageAsync2:(id)sender{
    
     if( [self setParams]){
    
         // Returns an initialized URL connection and begins to load the data for the URL request.
         if([[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]){
         
         };
         
     }
    
}

- (IBAction) uploadImageAsync3:(id)sender{
    
    if( [self setParams]){
        
       //Creates and returns an initialized URL connection and begins to load the data for the URL request.
        
        if([NSURLConnection connectionWithRequest:request delegate:self]){
            
        };
    }
    
}

-(void) initPB{
    indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    indicator.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width)/2, ([UIScreen mainScreen].bounds.size.height)/2 , 40.0, 40.0);
    indicator.center = self.view.center;
    [self.view addSubview:indicator];
    [indicator bringSubviewToFront:self.view];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
}

#pragma mark NSURLConnection Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now
    
    
    response.text = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
    NSLog(@"_responseData %@", response.text);
    
    [indicator stopAnimating];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
    // Check the error var
    
    NSLog(@"didFailWithError %@", error);
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

Now we go to the server side.

Please note the server file path in the code.
You must create a directory named “uploads” in the server before running the application.
Also Make sure that your server is running before you execute.

Refer the below Screenshot.

Upload Image To server using NSURLConnection

<?php
$target_path1 = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
    echo "The file ".  basename( $_FILES['uploaded_file']['name']).
    " has been uploaded to ".$target_path1;;
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploaded_file']['name']);
    echo "target_path: " .$target_path1;
}
?>

You can download the complete source code from here.

Upload Image To server using NSURLConnection

6 thoughts on “NSURLConnection – A Simple example – Upload image to server using POST method.

  1. Pingback: How to Create php file to upload image to server in php for ios? - BlogoSfera

  2. Jens Chr. Thomsen

    Hi

    I have used this code in one of my Apps and I have ruined into a small problem. If the image is to big I get an error when trying to upload it to the server.

    Is there anywhere in your code where I can set the limit for the files?

    Reply
    1. James Post author

      You can have your own logic for that. Set the limit for a file size while the user selects an image and Alert the User.

      Reply
  3. Art Farrell

    Since revising the “imagePickerController” method to convert images to NSData, using “UIImageJPEGRepresentation,” I have no problem uploaded photos to the server from my iPhone!

    What I’d like to do is revise the Xcode, and php file, to assign filenames to the photos before uploaded so that they appears in the “Uploads” directory on the server with the assigned filename rather than just titled “uploads.”

    Quite frankly, I’ve been unable to decipher the “setParams” code to accomplish my objective!

    Help! Please be kind, I’m 81, don’t time have to dither over, what will be a minor, but semi-important function, within the app I’m trying to roll out!

    Thanks, Art

    Reply
  4. Shaik Baji

    Hey can I have your project code or zip file please I have done all the thing. but it was loading and loading for hours not uploading the image to server side

    Reply
    1. James Post author

      Shaik,

      I dont have a project zip file.

      Check below points

      1. Make sure you have good internet connection
      2. Uploaded file is not too big
      3. Your server folder has write permission.
      4. Your server code is correct.

      Reply

Leave a Reply to Jens Chr. Thomsen Cancel reply

Your email address will not be published. Required fields are marked *