私のアプリでは、アプリがバックグラウンドに入ったときにサーバーにデータをアップロードしようとしています。これは私が使用しているコードです:
セッション
self.session = [self backgroundSession];
これが私のセッションのセットアップ方法です
- (NSURLSession *)backgroundSession
{
static NSURLSession *session = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.uploadSession"];
configuration.HTTPMaximumConnectionsPerHost = 1;
session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
});
return session;
}
アップロードを開始
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[self uploadPossibleDrives];
}
アップロード
// Start uploading the remaing gps log in th right order:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue setMaxConcurrentOperationCount:1];
for (int i = 0; i < arrayOfGPSLogChunks.count; i++)
{
// This will ensure the chunks are sent in the right order
// Add an operation as a block to a queue:
[queue addOperationWithBlock: ^ {
NSData *requestData;
NSMutableURLRequest *request;
if (i == 0)
{
NSLog(@"Initial drive upload %i",ID.integerValue);
requestData = [NSJSONSerialization dataWithJSONObject:historyToUpload options:NSJSONWritingPrettyPrinted error:nil];
request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:kInitialUploadDriveURL];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
}
else
{
NSLog(@"Chunk %i",i);
NSMutableDictionary *chunk = [[NSMutableDictionary alloc] init];
[chunk setObject:driveID forKey:@"driveID"];
[chunk setObject:[arrayOfGPSLogChunks objectAtIndex:i] forKey:@"gpsLog"];
requestData = [NSJSONSerialization dataWithJSONObject:chunk options:NSJSONWritingPrettyPrinted error:nil];
request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:kUploadDrivesChunkURL]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
}
NSLog(@"_session: %@",self.session);
NSLog(@"request: %@",request);
NSLog(@"requestData: %lu",(unsigned long)requestData.length);
NSLog(@"uploadTask: %@",self.uploadTask);
self.uploadTask = [self.session uploadTaskWithRequest:request fromData:requestData];
[self.uploadTask resume];
if (i == arrayOfGPSLogChunks.count-1)
{
// All gps logs were uploaded so now we save its state as 'uploaded to server':
NSLog(@"Finished sending to server!");
[self setSentToServerForDriveID:ID];
}
}];
}
エラー
今ここに私が得るエラーがあります:
誰かが私を助けてくれることを願っています。私が知っていることはすべて調べましたが、何がうまくいかないのかわかりません。ブロックを使用せずにアップロードも試みましたが、結果は同じです。
どんな助けでも大歓迎です!