在iOS中执行获取请求时应用程序冻结

时间:2014-04-16 09:17:43

标签: ios multithreading http get

我正在请求需要一些时间来提供响应的API,因此在此期间不能执行其他操作。例如后退按钮或Tabs未按下。我正在使用以下代码:

NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration   defaultSessionConfiguration];

NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];

NSURL * url = [NSURL URLWithString:urlString];
NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithURL:url
                                                    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                        if(error == nil)
                                                        {   
                                                        }else{
                                                        }
                                                    }];

    [dataTask resume];

任何人都可以建议我的应用程序在此操作期间冻结的原因。提前谢谢。

2 个答案:

答案 0 :(得分:0)

因为您正在主线程中执行操作,所以您需要在后台线程中执行此任务。

为此你可以使用NSOperationQueue并添加你api调用的操作。

参见belo链接

NSOperation and NSOperationQueue working thread vs main thread

How To Use NSOperations and NSOperationQueues

Working with the NSOperationQueue Class

或者您也可以使用DispatchQueue

请参阅:Multithreading and Grand Central Dispatch on iOS for Beginners Tutorial

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    // simply call your function here

});

答案 1 :(得分:0)

你正在主线程swhich中断app执行操作。你应该通过GCD在后台通过创建异步请求在后台下载数据来执行此操作,它不会中断你的应用程序执行。

dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(concurrentQueue, ^{    
  NSURL * url = [NSURL URLWithString:urlString];
NSData *response = [[NSData alloc] initWithContentsOfURL:url];

// above code will download data in background 
dispatch_async(dispatch_get_main_queue(), ^{
   // here you can access main thread of application and do something here
   });
 });
相关问题