2

I have this code below which sends an image and some text to my server:

 NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];

    self.session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate:self delegateQueue: nil];

    NSString *requestURL = @"http://www.website.com.br/receive.php?name=StackOverflow";

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestURL]];

    [request setHTTPMethod:@"POST"];

    UIImage *imagem = [UIImage imageNamed:@"Image.jpg"];

    NSData *imageData = UIImageJPEGRepresentation(imagem, 1.0);

    self.uploadTask = [self.session uploadTaskWithRequest:request fromData:imageData];

    [self.uploadTask resume];


-(void)URLSession:(NSURLSession *)session
         dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{

    NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",newStr);
}

PHP

<?php
echo $_POST['name'];
?>

The problem with this code is that the didReceiveData method does not receive the data going to the server, it only gets an NSData when I put this code in php file:

print_r($_FILES);

And yet it returns an empty array, why this is happening?

Solved

Well, I solved my problem, lets go, In .h file you need to implement this protocols and one property:

< NSURLSessionDelegate, NSURLSessionTaskDelegate>
@property (nonatomic) NSURLSessionUploadTask *uploadTask;

whereas in .m file there is a method of IBAction type and that it is connected to a particular button existing in our view, we need only do this:

- (IBAction)start:(id)sender {

    if (self.uploadTask) {
        NSLog(@"Wait for this process finish!");
        return;
    }

   NSString *imagepath = [[self applicationDocumentsDirectory].path stringByAppendingPathComponent:@"myImage.jpg"];
    NSURL *outputFileURL = [NSURL fileURLWithPath:imagepath];


    // Define the Paths
    NSURL *icyURL = [NSURL URLWithString:@"http://www.website.com/upload.php"];

    // Create the Request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:icyURL];
    [request setHTTPMethod:@"POST"];

    // Configure the NSURL Session
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.sometihng.upload"];

    NSURLSession *upLoadSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];

    // Define the Upload task
    self.uploadTask = [upLoadSession uploadTaskWithRequest:request fromFile:outputFileURL];

    // Run it!
    [self.uploadTask resume];

}

And implement some delegates methods:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {

    NSLog(@"didSendBodyData: %lld, totalBytesSent: %lld, totalBytesExpectedToSend: %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);

}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { 
    if (error == nil) {
        NSLog(@"Task: %@ upload complete", task);
    } else {
        NSLog(@"Task: %@ upload with error: %@", task, [error localizedDescription]);
    }
}

And for finish, you need create a PHP file with this code:

<?php

$fp = fopen("myImage.jpg", "a");//If image come is .png put myImage.png, is the file come is .mp4 put myImage.mp4, if .pdf myImage.pdf, if .json myImage.json ...

$run = fwrite($fp, file_get_contents("php://input"));

fclose($fp);

?>
LettersBa
  • 747
  • 1
  • 8
  • 27

2 Answers2

2

An example of code to upload image to dropbox.

// 1. config
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];

// 2. if necessary set your Authorization HTTP (example api)
// [config setHTTPAdditionalHeaders:@{@"<setYourKey>":<value>}];

// 3. Finally, you create the NSURLSession using the above configuration.
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

// 4. Set your Request URL (example using dropbox api)
NSURL *url = [Dropbox uploadURLForPath:<yourFullPath>];;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

// 5. Set your HTTPMethod POST or PUT
[request setHTTPMethod:@"PUT"];

// 6. Encapsulate your file (supposse an image)
UIImage *image = [UIImage imageNamed:@"imageName"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

// 7. You could try use uploadTaskWithRequest fromData
NSURLSessionUploadTask *taskUpload = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
    if (!error && httpResp.statusCode == 200) {

        // Uploaded

    } else {

       // alert for error saving / updating note
       NSLog(@"ERROR: %@ AND HTTPREST ERROR : %ld", error, (long)httpResp.statusCode);
      }
}];

- (NSURL*)uploadURLForPath:(NSString*)path
{
    NSString *urlWithParams = [NSString stringWithFormat:@"https://api-content.dropbox.com/1/files_put/sandbox/%@/%@",
                               appFolder,
                               [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];    
    NSURL *url = [NSURL URLWithString:urlWithParams];
    return url;
}
J. Lopes
  • 1,336
  • 16
  • 27
  • How we can pass parameters with file? – gypsicoder Oct 19 '15 at 07:07
  • @gypsicoder you can use `[config setHTTPAdditionalHeaders:@{@"Authorization": [Dropbox apiAuthorizationHeader]}];` for example to add dropbox authorization to the header - see more details here [link](https://www.dropbox.com/developers-v1/core/docs#oa2-authorize) - api – J. Lopes Oct 21 '15 at 01:58
0

You should convert your NSData into a more manageable format like an NSArray. To do so you must try something like:

NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data] 
Neeku
  • 3,646
  • 8
  • 33
  • 43
  • I have two NSDatas inside my code, one for send the data, and other to receive, how i put your code, in both? – LettersBa Feb 18 '15 at 02:09
  • I used in the method didReceiveData: to unarchive the data and I receive a crash error : incomprehensible archive (0x41, 0x72, 0x72, 0x61, 0x79, 0xa, 0x28, 0xa)' – LettersBa Feb 18 '15 at 02:10
  • Ok, sorry I was away from my computer today. You can add your solution as an answer to your own question rather than updating your question; and upvote the other answers if they have been helpful, too. – Neeku Feb 18 '15 at 23:19