How can I POST parameters by using NSURLSessionUploadTask from iOS background?

2.3k views Asked by At

I would like to send a POST massage with parameters by using NSURLSessionUploadTask from iOS(later than iOS7) background then take out parameters by using $_POST['parameter'] at my .php.

I knew that I have to use "uploadTaskWithRequest: fromFile:" from background but how can I use "file" instead of POST parameters?

I am trying like this. Any solution. Thanks.

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
NSURL *url = [NSURL URLWithString:@"http://some_server/some.php"];
NSString *identifier = @"identifier";
NSURLSessionConfiguration *configration = [NSURLSessionConfiguration backgroundSessionConfiguration:identifier];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
NSURLSession *session = [NSURLSession sessionWithConfiguration:configration];

NSString *parameters = @"parameter1=value1&parameter2=value2";
[request setHTTPBody:[parameters dataUsingEncoding:NSUTF8StringEncoding]];

NSString *sampleText = @"test";
NSString *filePath = [[self applicationDocumentsDirectory].path stringByAppendingPathComponent:@"test.txt"];
NSError *error;
[sampleText writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

filePath = [NSString stringWithFormat:@"file://%@", filePath];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:[NSURL URLWithString:filePath]];

[task resume];

completionHandler(UIBackgroundFetchResultNoData);
}

I solved this issue like below.

NSURL *url = [NSURL URLWithString:@"http://..."];
NSURLSessionConfiguration *configuration;
configuration.timeoutIntervalForRequest = 5;
configuration.timeoutIntervalForResource = 5;
configuration.HTTPMaximumConnectionsPerHost = 1;
configuration.allowsCellularAccess = YES;
configuration.networkServiceType = NSURLNetworkServiceTypeBackground;
configuration.discretionary = NO;
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
                                                              delegate:self
                                                         delegateQueue:[NSOperationQueue mainQueue]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"PUT";

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                    object, @"key", nil];

NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil];

NSString *path = [[self applicationDocumentsDirectory].path stringByAppendingPathComponent:@"json.data"];
[data writeToFile:path atomically:YES];

path = [NSString stringWithFormat:@"file://%@", path];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:[NSURL URLWithString:path]];

[task resume];
1

There are 1 answers

0
skyElements On

Here is my solution.

NSURL *url = [NSURL URLWithString:@"http://..."];
NSURLSessionConfiguration *configuration;
configuration.timeoutIntervalForRequest = 5;
configuration.timeoutIntervalForResource = 5;
configuration.HTTPMaximumConnectionsPerHost = 1;
configuration.allowsCellularAccess = YES;
configuration.networkServiceType = NSURLNetworkServiceTypeBackground;
configuration.discretionary = NO;
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
                                                          delegate:self
                                                     delegateQueue:[NSOperationQueue mainQueue]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"PUT";

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                object, @"key", nil];

NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil];

NSString *path = [[self applicationDocumentsDirectory].path stringByAppendingPathComponent:@"json.data"];
[data writeToFile:path atomically:YES];

path = [NSString stringWithFormat:@"file://%@", path];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:[NSURL URLWithString:path]];

[task resume];

.php file in server is like below.

<?php

$put = fopen("php://input", "r");
if (!$put)
{   
    fclose($put);   
    exit();
}

$lines = "";
while ($line = fgets($put))
{   
    $lines = $lines . $line;
}   
$lines = str_replace(array("\r", "\n"), '', $lines);
$json = json_decode($lines,  true);
fclose($put);

//Do something with $json.

?>