我正在尝试在我的项目中使用 NSURLSession。这就是这种情况,我想检查是否已经存在具有相同请求的任何任务。所以我用getTasksWithCompletionHandler
检查,如果没有,则恢复块中的任务。但是当我这样做时,数组中总是没有其他任务。
我错过了什么?
这是我的代码:
#import "HttpRequestHelper.h"
@implementation HttpRequestHelper
+(NSURLSession *)sharedDefaultSession{
static dispatch_once_t once;
static NSURLSession * defaultSession;
dispatch_once(&once, ^{
NSURLSessionConfiguration * configure = [NSURLSessionConfiguration defaultSessionConfiguration];
configure.HTTPMaximumConnectionsPerHost = 5;
configure.timeoutIntervalForRequest = kTimeOutInterval;
configure.timeoutIntervalForResource = kTimeOutInterval;
defaultSession = [NSURLSession sessionWithConfiguration:configure delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
});
return defaultSession;
}
+(void)resultFromRequest:(NSURLRequest *)request withCompleter:(downloadCompleter)completer{
NSURLSessionDataTask * dataTask = [[self sharedDefaultSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// NSLog(@"response %@",response);
// NSLog(@"url:%@\nData:%@",request.URL,[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
if (!error) {
NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) {
completer([self jsonObjectFromData:data]);
} else {
completer(nil);
// handle http error
}
} else {
completer(nil);
NSLog(@"network error %@",error.localizedDescription);
// handle network error
}
}];
NSLog(@"check %@",dataTask);
[self checkAndResumeTask:dataTask];
}
+(void)checkAndResumeTask:(NSURLSessionTask *)task{
[[self sharedDefaultSession] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
BOOL isNewTask = (![self containTask:task inTaskArray:dataTasks]&&![self containTask:task inTaskArray:downloadTasks]);
NSLog(@"isNewTask : %d %@",isNewTask,[self sharedDefaultSession] );
if (isNewTask) {
if (!IS_LOWER_IOS8) {
task.priority = NSURLSessionTaskPriorityHigh;
}
NSLog(@"%@ resume",task);
[task resume];
} else {
[task cancel];
}
}];
}
+(BOOL)containTask:(NSURLSessionTask *)task inTaskArray:(NSArray *)taskArray{
NSString * taskIndepentId = [task.originalRequest valueForHTTPHeaderField:IndependentID]?:@"";
NSString * taskUrlString = task.originalRequest.URL.absoluteString;
for (NSURLSessionTask * oldTask in taskArray) {
if (!IS_LOWER_IOS8) {
oldTask.priority = NSURLSessionTaskPriorityDefault;
}
NSString * oldTaskIndepentId = [oldTask.originalRequest valueForHTTPHeaderField:IndependentID]?:@"";
NSString * oldTaskUrlString = oldTask.originalRequest.URL.absoluteString;
if ([taskIndepentId isEqualToString:oldTaskIndepentId] && [taskUrlString isEqualToString:oldTaskUrlString] && oldTask!=task) {
return YES;
}
}
return NO;
}
+(id)jsonObjectFromData:(NSData*)data{
NSError * dataError;
NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&dataError];
if (dataError) {
NSLog(@"json data error : %@",dataError);
}
return dic;
}
+(void)cancelTaskForRequest:(NSURLRequest *)request{
[[self sharedDefaultSession] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
[self cancelRequest:request ForArrayTasks:dataTasks];
[self cancelRequest:request ForArrayTasks:uploadTasks];
[self cancelRequest:request ForArrayTasks:downloadTasks];
}];
}
+(void)cancelRequest:(NSURLRequest *)request ForArrayTasks:(NSArray *)arrayTasks{
for (NSURLSessionTask * task in arrayTasks) {
NSLog(@"task %@",task);
NSURLRequest * requestTask = task.originalRequest;
BOOL isSameURL = [requestTask.URL.absoluteString isEqualToString:request.URL.absoluteString];
BOOL isSameID = [[requestTask valueForHTTPHeaderField:IndependentID] isEqualToString:[request valueForHTTPHeaderField:IndependentID]];
if (isSameURL && isSameID) {
[task cancel];
}
}
}
@end
我已经尝试 add [dataTask resume];
before check checkAndResumeTask:
,并且任务将在数组中getTasksWithCompletionHandler
,但是在恢复之前如何检查?
这是正确的做法吗?
我将不胜感激任何评论,谢谢。
- - - - 编辑 - - - -
@dgatwood:我确定其他任务正在运行
+(void)checkAndResumeTask:(NSURLSessionTask *)task{
NSLog(@"\ncheck task %@ \nfor URL %@ \nin thread %@",task,task.originalRequest.URL.absoluteString,[NSOperationQueue currentQueue]);
[[self sharedDefaultSession] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
NSLog(@"\ncheck task %@ \nfor URL %@ \nin thread %@ \n\n old tasks: %@,\n%@",task,task.originalRequest.URL.absoluteString,[NSOperationQueue currentQueue],dataTasks,downloadTasks);
BOOL isNewTask = (![self containTask:task inTaskArray:dataTasks]&&![self containTask:task inTaskArray:downloadTasks]);
NSLog(@"isNewTask : %d %@",isNewTask,[self sharedDefaultSession] );
if (isNewTask) {
if (!IS_LOWER_IOS8) {
task.priority = NSURLSessionTaskPriorityHigh;
}
[task resume];
NSLog(@"\nresume task :%@",task);
} else {
[task cancel];
}
}];
}
我在代码中、块之前、块之后和恢复任务之后打印信息。
我用相同的请求调用了三个任务。
下面是我的结果
您可以看到2015-09-04 01:59:45.216 XXX[26387:1632660]
**resume task :<__NSCFLocalDataTask: 0x7fa428e81a40>{ taskIdentifier: 1 } { running }**
此任务运行后,但此之后的块返回数组中仍然没有任务。
这是因为块在第一个任务恢复之前已经获得了数组吗?还是我出了什么问题?
2015-09-04 01:59:45.130 XXX[26387:1632660]
check task <__NSCFLocalDataTask: 0x7fa428e81a40>{ taskIdentifier: 1 } { suspended }
for URL https://XXX/AppApi/api/account/BonusDetails
in thread <NSOperationQueue: 0x7fa428d05f70>{name = 'NSOperationQueue Main Queue'}
2015-09-04 01:59:45.131 XXX[26387:1632660]
check task <__NSCFLocalDataTask: 0x7fa42b034e70>{ taskIdentifier: 2 } { suspended }
for URL https://XXX/AppApi/api/account/BonusDetails
in thread <NSOperationQueue: 0x7fa428d05f70>{name = 'NSOperationQueue Main Queue'}
2015-09-04 01:59:45.132 XXX[26387:1632660]
check task <__NSCFLocalDataTask: 0x7fa42b037180>{ taskIdentifier: 3 } { suspended }
for URL https://XXX/AppApi/api/account/BonusDetails
in thread <NSOperationQueue: 0x7fa428d05f70>{name = 'NSOperationQueue Main Queue'}
2015-09-04 01:59:45.215 XXX[26387:1632660]
check task <__NSCFLocalDataTask: 0x7fa428e81a40>{ taskIdentifier: 1 } { suspended }
for URL https://XXX/AppApi/api/account/BonusDetails
in thread <NSOperationQueue: 0x7fa428d05f70>{name = 'NSOperationQueue Main Queue'}
old tasks: (
),
(
)
2015-09-04 01:59:45.216 XXX1632660] isNewTask : 1 <__NSURLSessionLocal: 0x7fa428e80d80>
2015-09-04 01:59:45.216 XXX[26387:1632660]
**resume task :<__NSCFLocalDataTask: 0x7fa428e81a40>{ taskIdentifier: 1 } { running }**
2015-09-04 01:59:45.255 XXX[26387:1632660]
check task <__NSCFLocalDataTask: 0x7fa42b034e70>{ taskIdentifier: 2 } { suspended }
for URL XXX/AppApi/api/account/BonusDetails
in thread <NSOperationQueue: 0x7fa428d05f70>{name = 'NSOperationQueue Main Queue'}
old tasks: (
),
(
)
2015-09-04 01:59:45.255 XXX[26387:1632660] isNewTask : 1 <__NSURLSessionLocal: 0x7fa428e80d80>
2015-09-04 01:59:45.255 XXX[26387:1632660]
resume task :<__NSCFLocalDataTask: 0x7fa42b034e70>{ taskIdentifier: 2 } { running }
2015-09-04 01:59:45.256 XXX[26387:1632660]
check task <__NSCFLocalDataTask: 0x7fa42b037180>{ taskIdentifier: 3 } { suspended }
for URL https://XXX/AppApi/api/account/BonusDetails
in thread <NSOperationQueue: 0x7fa428d05f70>{name = 'NSOperationQueue Main Queue'}
old tasks: (
),
(
)