13

I'm trying to port my old code for loading files from NSOperationQueue to NSURLSession. Almost everything is alright but I can't find how to set priority for loading different tasks. Does anybody know if NSURLSession supports prioritising at all? And if yes could you show me how, please?

Thanks in advance!

Rost

Rostyslav Druzhchenko
  • 3,673
  • 3
  • 33
  • 38
  • 1
    The only prioritisation I've seen comes from [networkServiceType](https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionConfiguration_class/Reference/Reference.html#//apple_ref/occ/instp/NSURLSessionConfiguration/networkServiceType). – Matt Gibson May 12 '14 at 06:27
  • Never seen/heard of prioritizing with NSURLSession- I think you should schedule the taskQueue with short sets of tasks instead of loading the whole bunch. – Xcoder Sep 01 '14 at 13:53
  • Seems that the priorities are per task, not session. BTW, I believe you could use HTTPMaximumConnectionsPerHost to prioritize your session. – ox_ Feb 11 '15 at 15:39

2 Answers2

11

There is a property on NSURLSessionTask

@property float priority NS_AVAILABLE(10_10, 8_0);

Its description says

  • Sets a scaling factor for the priority of the task. The scaling factor is a value between 0.0 and 1.0 (inclusive), where 0.0 is considered the lowest priority and 1.0 is considered the highest.
  • The priority is a hint and not a hard requirement of task performance. The priority of a task may be changed using this API at any time, but not all protocols support this; in these cases, the last priority that took effect will be used. If no priority is specified, the task will operate with the default priority
  • as defined by the constant NSURLSessionTaskPriorityDefault. Two additional priority levels are provided: NSURLSessionTaskPriorityLow and NSURLSessionTaskPriorityHigh, but use is not restricted to these.

I use it between a downloadTask and dataTask that could trigger simultaneously in our app and the dataTask waits for the download forever. But this fixes the issue

dataTask.priority = NSURLSessionTaskPriorityHigh;
tomahh
  • 13,441
  • 3
  • 49
  • 70
Irfanlone
  • 564
  • 7
  • 16
3

I'm not sure if this is available yet in iOS 8, but I found these lines in NSURLSession.h file

FOUNDATION_EXPORT const float NSURLSessionTaskPriorityDefault NS_AVAILABLE(10_10, 8_0);
FOUNDATION_EXPORT const float NSURLSessionTaskPriorityLow NS_AVAILABLE(10_10, 8_0);
FOUNDATION_EXPORT const float NSURLSessionTaskPriorityHigh NS_AVAILABLE(10_10, 8_0);

The apple iOS 8.1 release note is suggesting that these will be available in 8.1 though.

Pahnev
  • 716
  • 5
  • 26
  • 1
    These are supposed to be available in iOS 8 and later, but it appears there is a bug when using these in an optimized build. https://openradar.appspot.com/23956486 – Dennis Munsie Apr 28 '16 at 13:33