Question

I am requesting an API that takes some time to give response, so during that time no other operation can be performed. e.g. back button or Tabs are not pressed. I am Using the following code:

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];

Can anyone Suggest why my app is freezing during this operation. Thanks in advance.

Was it helpful?

Solution

Because you are performing operation in main thread, you need to do this task in background thread.

For this you can use NSOperationQueue and add a operation of you api calling.

see belo links

NSOperation and NSOperationQueue working thread vs main thread

How To Use NSOperations and NSOperationQueues

Working with the NSOperationQueue Class

or you can also use DispatchQueue

see : 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

});

OTHER TIPS

you are doing operation on main thread swhich interrupt app execution. you should do this operation in background through GCD by creating async request to download data in background it will not interrupt your app execution.

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
   });
 });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top