如何使用iOS背景中的NSURLSessionUploadTask来发布参数?

时间:2014-11-29 09:55:00

标签: ios objective-c nsurlsession nsurlsessionuploadtask

我想通过使用来自iOS(晚于iOS7)背景的NSURLSessionUploadTask发送带参数的POST按摩,然后在我的.php中使用$ _POST ['参数']取出参数。

我知道我必须使用" uploadTaskWithRequest:fromFile:"从背景但我怎样才能使用" file"而不是POST参数?

我是这样想的。任何解决方案感谢。

- (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);
}

我解决了这个问题如下。

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 个答案:

答案 0 :(得分:0)

这是我的解决方案。

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文件如下所示。

<?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.

?>