使用 NSOperationQueue 在后台下载表单

Using NSOperationQueue for downloading forms in background

我需要从网上下载一些表格 service.For 我已经像这样使用了 NSOperationQueue

operationQueue = [NSOperationQueue new];
    for (int i=0;i<[tempArray count];i++) {
        CheckList * checklist = (CheckList *)[tempArray objectAtIndex:i];

        NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                                selector:@selector(downloadChecklistsInBackground:)
                                                                                  object:checklist];
        [operationQueue addOperation:operation];

想法是,它应该在不影响屏幕操作的情况下执行。在 UI 中,每个 forms.So 都有单独的下载按钮,如果用户单击其中任何一个,应立即下载并从后台删除 process.The代码如下。

-(void)downloadChecklistsInBackground:(CheckList *)checklist
{
    BOOL isDone = NO;
    for (int j=0; j<[selectedArray count]; j++) {
        if([checklist.checklistId isEqualToString:[selectedArray objectAtIndex:j]])
        {
            isDone = YES;

        }
    }
    if(!isDone)
    {
        [backGroundQueueArr addObject:checklist];

        NSString * urlStr = [[BASE_URL stringByAppendingString:DOWNLOAD_CHECKLIST_URL] stringByAppendingFormat:@"%@/%d/%@/%@/%@",[ChecklistSingleton sharedSingleton].userSSO,[checklist.checklistId intValue],checklist.language,checklist.baseFormId,checklist.versionNo];
        NSURL * url = [NSURL URLWithString:urlStr];
        NSLog(@"url is %@",url);

        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

        NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
        AppDelegate * appDelegateObj = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [request setValue:[NSString stringWithFormat:@"Bearer %@",appDelegateObj.accessToken ]forHTTPHeaderField:@"Authorization"];
        [request setTimeoutInterval:240.0];
        [request setValue:@"Application/JSON" forHTTPHeaderField:@"Content-Type"];
        NSURLSessionDataTask * downloadTask =[session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error)
                                              {
                                                  NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                                  NSLog(@"response is %@",str);
                                              }];
        [downloadTask resume];

    }


}
-(void)downloadCecklistWithChecklist:(CheckList *)check5
{

    [selectedArray addObject:check5];
    BOOL isDownloaded = NO;
    for (int j=0; j<[backGroundQueueArr count]; j++) {
        CheckList * checklistTobeChecked = [backGroundQueueArr objectAtIndex:j];
        if([checklistTobeChecked.checklistId isEqualToString:check5.checklistId])
        {
            isDownloaded = YES;
        }
    }
    if(!isDownloaded)
    {

    NSString * urlStr = [[BASE_URL stringByAppendingString:DOWNLOAD_CHECKLIST_METADATA_SUBURL] stringByAppendingFormat:@"%@/%d/%@/%@/%@",[ChecklistSingleton sharedSingleton].userSSO,[check5.checklistId intValue],check5.language,check5.baseFormId,check5.versionNo];
    NSURL * url = [NSURL URLWithString:urlStr];
    NSLog(@"url is %@",url);

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
    AppDelegate * appDelegateObj = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [request setValue:[NSString stringWithFormat:@"Bearer %@",appDelegateObj.accessToken ]forHTTPHeaderField:@"Authorization"];
    [request setTimeoutInterval:240.0];
    [request setValue:@"Application/JSON" forHTTPHeaderField:@"Content-Type"];
    NSURLSessionDataTask * downloadTask =[session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error)
                                          {
                                              NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                              NSLog(@"response is specific %@",str);
                                          }];
    [downloadTask resume];
    }


}

能否请您帮助我了解 this.I 的正确方法,请知道,这段代码没有正确实现线程。请提前指导我this.Thank。

NSURLSession 已经包装了异步下载操作,在这种情况下您不必从 NSInvocationOperation 调用它。 我建议你:

1) 使用每个清单索引的索引初始化按钮标签

2) 保存下载检查列表的 NSMutableIndexSet

3) 下载时禁用点击按钮

4) 添加下载清单索引

5) 检查是否所有列表都已下载,如果是,则从 tempArray

中删除所有列表

6) 启用按钮

为所有按钮创建通用事件,例如:

-(IBAction)myButtonClickEvent:(id)sender{

  // 2 - protects your data from being downloaded twice
  if([indexSet contains:sender.tag])
     return;
  // 3 - disable while downloading
  sender.enabled = NO;
  CheckList * check5 = [tempArray objectAtIndex : sender.tag];
  NSString * urlStr = [[BASE_URLstringByAppendingString:DOWNLOAD_CHECKLIST_METADATA_SUBURL] stringByAppendingFormat:@"%@/%d/%@/%@/%@",[ChecklistSingleton sharedSingleton].userSSO,[check5.checklistId intValue],check5.language,check5.baseFormId,check5.versionNo];
  NSURL * url = [NSURL URLWithString:urlStr];
  NSLog(@"url is %@",url);
  NSURLSessionConfiguration *config = [NSURLSessionConfiguration  defaultSessionConfiguration];
  NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

  NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
AppDelegate * appDelegateObj = (AppDelegate *)[[UIApplication sharedApplication] delegate];
 [request setValue:[NSString stringWithFormat:@"Bearer %@",appDelegateObj.accessToken ]forHTTPHeaderField:@"Authorization"];
 [request setTimeoutInterval:240.0];
 [request setValue:@"Application/JSON" forHTTPHeaderField:@"Content-Type"];
NSURLSessionDataTask * downloadTask =[session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error)
                                      {
                                          // 4 - add index of downloaded checklist
                                          [indexSet addIndex:sender.tag];
                                          //5 - remove all checklists if all of them are downloaded
                                          if([indexSet count]==[tempArray count])
                                                 [tempArray removeAllObjects];
                                          NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                          NSLog(@"response is specific %@",str);

                                          //6 - enable the button
                                          sender.enabled = YES;

                                      }];
[downloadTask resume];

}