在iOS Objective C中运行的后台会话中下载任务时,UI会阻塞

时间:2019-05-11 11:21:31

标签: ios objective-c ui-thread nsurlsessiondownloadtask background-thread

在后台会话中运行下载任务时,应用程序冻结并且UI被阻止

我的后台会议如下

-(NSURLSession *)backgroundSession
{
    if (session==nil) {
        NSURLSessionConfiguration *configuration;

        //        configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        if ([NSURLSessionConfiguration respondsToSelector:@selector(backgroundSessionConfigurationWithIdentifier:)]) {
            configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.xxx.xxx.BackgroundSession"];
        } else
        {
            configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.xxx.xxx.BackgroundSession"];
        }
        [configuration setSessionSendsLaunchEvents:YES];
        configuration.HTTPMaximumConnectionsPerHost = 1;
        session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    }
    return session;
}

[self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
        if ([downloadTasks count] > 0 ) {
            NSArray *filtered = [downloadTasks filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(self.taskDescription MATCHES %@)", [NSString stringWithFormat:@"SONGDATA_DOWNLOAD %@",songID]]];
            if([filtered count]>0)
            {
                for(NSURLSessionDownloadTask *PreviousDownloadTask in filtered)
                {
                    if(PreviousDownloadTask.state != NSURLSessionTaskStateRunning && PreviousDownloadTask.state != NSURLSessionTaskStateCompleted)
                    {
                        [PreviousDownloadTask resume];
                        NSLog(@"SONGDATA_DOWNLOAD already in queue %@ task Description %@",filtered,[NSString stringWithFormat:@"SONGDATA_DOWNLOAD %@",songID]);
                    }
                    return ;

                }
            }

        }
    }];





    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    self.downloadTask = [[self backgroundSession] downloadTaskWithRequest:request];
    downloadTask.taskDescription=[NSString stringWithFormat:@"SONGDATA_DOWNLOAD %@",songID];

    [self.downloadTask resume];

但是当请求发送失败并获得结果

xpc连接设置后台会话时发生错误:

  

Error Domain = NSCocoaErrorDomain Code = 4097“连接到名为服务   com.apple.nsurlsessiond“ UserInfo = {NSDebugDescription =连接到   名为com.apple.nsurlsessiond的服务}

几分钟,直到应用程序冻结,并且无法执行UI操作。

0 个答案:

没有答案