Difference between revisions of "macOS NSURLSession"

From Lazarus wiki
(New content - first draft)
 
(Example code: Fix thread synchronisation code)
 
(29 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
{{macOS NSURLSession}}
 +
 
== Overview ==
 
== Overview ==
  
Line 15: Line 17:
 
The NSURLSession API supports three types of sessions, as determined by the type of configuration object used to create the session:
 
The NSURLSession API supports three types of sessions, as determined by the type of configuration object used to create the session:
  
# Default sessions behave similarly to other Foundation methods for downloading URLs. They use a persistent disk-based cache and store credentials in the user’s keychain.
+
# Default sessions behave similarly to other Foundation methods for downloading URLs. They use a persistent disk-based cache and store credentials in the user’s keychain. A default session configuration object results in a session that behaves like an NSURLConnection object in its standard configuration. Altering a session configuration obtained through the defaultSessionConfiguration method does not change the default session configuration of which it is a copy.
# Ephemeral sessions do not store any data to disk; all caches, credential stores, and so on are kept in RAM and tied to the session. Thus, when your application invalidates the session, they are purged automatically.
+
# Ephemeral sessions do not store any data to disk; all caches, credential stores, and so on are kept in RAM and tied to the session. Thus, when your application invalidates the session, they are purged automatically. Ephemeral sessions are therefore ideal if you need to implement private browsing.
 
# Background sessions are similar to default sessions, except that a separate process handles all data transfers. Background sessions have some additional limitations:
 
# Background sessions are similar to default sessions, except that a separate process handles all data transfers. Background sessions have some additional limitations:
 
## The session must provide a delegate for uploads and downloads.
 
## The session must provide a delegate for uploads and downloads.
Line 23: Line 25:
 
## Redirects are always followed.
 
## Redirects are always followed.
 
## If the background transfer is initiated while the app is in the background, the configuration object’s discretionary property is treated as being true.
 
## If the background transfer is initiated while the app is in the background, the configuration object’s discretionary property is treated as being true.
 +
## Background configurations cannot be reused (ie you cannot use two background session configurations using the same configuration identifier).
  
 
=== Types of Tasks ===
 
=== Types of Tasks ===
  
An NSURLSession supports three types of tasks:
+
An NSURLSession supports four types of tasks:
  
 
* data tasks,
 
* data tasks,
Line 40: Line 43:
  
 
Web socket tasks exchange messages over TCP and TLS, using the WebSocket protocol defined in [https://tools.ietf.org/html/rfc6455 RFC 6455].
 
Web socket tasks exchange messages over TCP and TLS, using the WebSocket protocol defined in [https://tools.ietf.org/html/rfc6455 RFC 6455].
 +
 +
=== Asynchronicity ===
 +
 +
The NSURLSession API is highly asynchronous. It returns data to your application in one of two ways, depending on the methods you call:
 +
 +
* by calling a completion handler block when a transfer finishes successfully or with an error; or
 +
* by calling methods on the session’s delegate as data arrives and when the transfer is complete.
 +
 +
In addition to delivering this information to delegates, the NSURLSession provides status and progress properties that you can query if you need to make programmatic decisions based on the current state of the task (with the caveat that its state can change at any time).
  
 
=== Protocol support ===
 
=== Protocol support ===
Line 62: Line 74:
 
* A configuration object that governs the behaviour of that session and the tasks within it
 
* A configuration object that governs the behaviour of that session and the tasks within it
 
* Optionally, a delegate object to process incoming data as it is received and handle other events specific to the session and the tasks within it, such as server authentication, determining whether a resource load request should be converted into a download, and so on.
 
* Optionally, a delegate object to process incoming data as it is received and handle other events specific to the session and the tasks within it, such as server authentication, determining whether a resource load request should be converted into a download, and so on.
* If you do not provide a delegate, the NSURLSession object uses a system-provided delegate. In this way, you can readily use NSURLSession in place of existing code that uses the sendAsynchronousRequest:queue:completionHandler: convenience method on NSURLSession.
+
* If you do not provide a delegate, the NSURLSession object uses a system-provided delegate. In this way, you can readily use NSURLSession in place of existing code that uses the ''sendAsynchronousRequest:queue:completionHandler:'' convenience method on NSURLSession.
  
 
As these settings are contained in a separate configuration object, you can reuse commonly used settings in other sessions.
 
As these settings are contained in a separate configuration object, you can reuse commonly used settings in other sessions.
  
== Using system-provided delegates ==
+
== Retrieving data using system-provided delegates ==
  
This simple demonstration shows how to use NSURLSession and related classes to download and display a web page using NSURLSession as a drop-in replacement for the NSURLConnection sendAsynchronousRequest:queue:completionHandler: method. Using this method, you need to provide only two pieces of code in your application:
+
This simple demonstration shows how to use NSURLSession and related classes to download and display a web page using NSURLSession as a drop-in replacement for the [[macOS_NSURLConnection#Retrieving_data_asynchronously_using_a_completion_handler_block|''NSURLConnection sendAsynchronousRequest:queue:completionHandler:'']] method. Using this method, you need to provide only two pieces of code in your application:
  
* Code to create a configuration object and a session based on that object; and
+
# code to create a configuration object and a session based on that object; and
* A completion handler routine to do something with the data after it has been fully received.  
+
# code to implement a completion handler routine to do something with the data after it has been fully received.  
  
 
=== Example code ===
 
=== Example code ===
Line 88: Line 100:
 
   Dialogs,    // for ShowMessage
 
   Dialogs,    // for ShowMessage
 
   StdCtrls,  // for the button
 
   StdCtrls,  // for the button
   SysUtils,  // for sleep
+
   SysUtils,  // for IntToStr()
 
   CocoaAll,  // for NSData and other Cocoa types
 
   CocoaAll,  // for NSData and other Cocoa types
 
   CocoaUtils; // for NSStringString
 
   CocoaUtils; // for NSStringString
Line 99: Line 111:
 
   NSURLSession = objcclass external (NSObject)
 
   NSURLSession = objcclass external (NSObject)
 
   public
 
   public
     class function sessionWithConfiguration(configuration: NSURLSessionConfiguration): NSURLSession; message 'sessionWithConfiguration:';
+
     class function sessionWithConfiguration(configuration: NSURLSessionConfiguration): NSURLSession;  
 +
      message 'sessionWithConfiguration:';
 
   end;
 
   end;
  
 
   NSURLSessionAsynchronousConvenience = objccategory external (NSURLSession)
 
   NSURLSessionAsynchronousConvenience = objccategory external (NSURLSession)
     function dataTaskWithURL_completionHandler(url: NSURL; completionHandler: tBlock): NSURLSessionDataTask; message 'dataTaskWithURL:completionHandler:';
+
     function dataTaskWithURL_completionHandler(url: NSURL; completionHandler: tBlock): NSURLSessionDataTask;  
 +
      message 'dataTaskWithURL:completionHandler:';
 
   end;
 
   end;
  
Line 120: Line 134:
 
   Form1: TForm1;
 
   Form1: TForm1;
 
   myCache: NSURLcache;
 
   myCache: NSURLcache;
   webData: String = 'default';
+
   webData: String;
 
   webResponse: String;
 
   webResponse: String;
 
   webHTML: String;
 
   webHTML: String;
 
   webStatusCode: Integer;
 
   webStatusCode: Integer;
  webErrorCode: Integer = 0;
+
   webError: String;
   webError: String = 'default';
 
 
   webErrorReason: String;
 
   webErrorReason: String;
 +
  didFinish: PRTLEvent;
  
 
implementation
 
implementation
Line 182: Line 196:
 
         + LineEnding + LineEnding + 'Reason: ' + NSStringToString(connectionError.localizedDescription);
 
         + LineEnding + LineEnding + 'Reason: ' + NSStringToString(connectionError.localizedDescription);
 
     end;
 
     end;
 +
 +
  // notify main thread that completion handler thread has finished
 +
  RTLEventSetEvent(didFinish);
  
 
   {$IFDEF DEBUG}
 
   {$IFDEF DEBUG}
Line 196: Line 213:
 
   URL: NSURL;
 
   URL: NSURL;
 
begin
 
begin
 +
  // create event to synchronise completion handler background thread
 +
  // with the GUI main thread
 +
  didFinish := RTLEventCreate; 
 +
 
   // create default url session config
 
   // create default url session config
 
   urlSessionConfig := NSURLSessionConfiguration.defaultSessionConfiguration;
 
   urlSessionConfig := NSURLSessionConfiguration.defaultSessionConfiguration;
Line 210: Line 231:
  
 
   // set cache policy
 
   // set cache policy
   //urlSessionConfig.setRequestCachePolicy(NSURLRequestReloadIgnoringLocalCacheData);
+
   {$IFDEF DEBUG}
 +
  urlSessionConfig.setRequestCachePolicy(NSURLRequestReloadIgnoringLocalCacheData);
 +
  {$ELSE}
 
   urlSessionConfig.setRequestCachePolicy(NSURLRequestUseProtocolCachePolicy);
 
   urlSessionConfig.setRequestCachePolicy(NSURLRequestUseProtocolCachePolicy);
 +
  {$ENDIF}
  
 
   // create a session for configuration
 
   // create a session for configuration
Line 217: Line 241:
  
 
   // create NSURL
 
   // create NSURL
   URL := NSURL.URLWithString(NSSTR(PAnsiChar('https://sentinel.sentry.org/xx')));
+
   URL := NSURL.URLWithString(NSSTR(PAnsiChar('https://sentinel.sentry.org/')));
 
   if(Url = Nil) then
 
   if(Url = Nil) then
 
       ShowMessage('NSURL.URLWithString failed!');
 
       ShowMessage('NSURL.URLWithString failed!');
Line 224: Line 248:
 
   urlSession.dataTaskWithURL_completionHandler(URL, @myCompletionHandler).resume;
 
   urlSession.dataTaskWithURL_completionHandler(URL, @myCompletionHandler).resume;
  
   // wait until globals accessible in main thread
+
   // wait for completion handler to finish
  // - the completion handler does not run in the main thread
+
   RTLEventWaitFor(didFinish);  
   while((webData = 'default')) AND (webError = 'default') do
 
    Sleep(50);
 
  
 
   // display results
 
   // display results
Line 242: Line 264:
 
       ShowMessage('Web page: ' + LineEnding + LineEnding + webHTML);
 
       ShowMessage('Web page: ' + LineEnding + LineEnding + webHTML);
 
     end;
 
     end;
 +
 +
  // housekeeping
 +
  RTLeventdestroy(didFinish);
 
end;
 
end;
  
Line 248: Line 273:
 
   myCache.release;
 
   myCache.release;
 
end.</syntaxhighlight>
 
end.</syntaxhighlight>
 +
 +
===== Compilation note =====
 +
 +
To compile the above code successfully you are going to have to add the missing ''initWithData'' function to the ''NSString'' class by editing <tt>/usr/local/share/fpcsrc/fpc-[3.0.4|3.2.0|3.3.1]/packages/cocoaint/src/foundation/NSString.inc</tt> to add the missing (highlighted) function as follows:
 +
 +
<syntaxhighlight lang=pascal highlight=7>
 +
--- NSString.inc        (revision 45778)
 +
+++ NSString.inc        (working copy)
 +
@@ -105,6 +105,7 @@
 +
    function characterAtIndex (index: NSUInteger): unichar; message 'characterAtIndex:';
 +
    function init: instancetype; message 'init'; { NS_DESIGNATED_INITIALIZER }
 +
    function initWithCoder (aDecoder: NSCoder): instancetype; message 'initWithCoder:'; { NS_DESIGNATED_INITIALIZER }
 +
+    function initWithData(data: NSData; encoding: NSStringEncoding) : instancetype; message 'initWithData:encoding:';
 +
 +
    { Adopted protocols }
 +
    function copyWithZone (zone: NSZonePtr): id; message 'copyWithZone:';
 +
</syntaxhighlight>
 +
 +
and then recompile the FPC source. This has been tested with FPC 3.0.4, FPC 3.2.0 and FPC 3.3.1. Note that for FPC 3.0.4 you need to replace "instancetype" in the highlighted line with "id"
 +
 +
I use the following script (for FPC 3.3.1; substitute your FPC version numbers as appropriate) to recompile FPC:
 +
 +
<syntaxhighlight lang=sh highlight=3>
 +
#!/bin/sh
 +
cd /usr/local/share/fpcsrc/fpc-3.3.1/
 +
make clean all FPC=/usr/local/lib/fpc/3.3.1/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64 OPT="-XR/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/"
 +
make install FPC=/usr/local/lib/fpc/3.3.1/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64
 +
</syntaxhighlight>
 +
 +
* Note 1: The highlighted line(s) above should be all on one line.
 +
* Note 2: You will almost certainly have to use ''sudo'' to execute that script successfully or face permissions problems.
 +
 +
== Retrieving data using a custom delegate ==
 +
 +
When using a custom delegate to retrieve data, the delegate must implement at least the following methods:
 +
 +
* URLSession:dataTask:didReceiveData: Tells the delegate that the data task has received some of the expected data.
 +
* URLSession:task:didCompleteWithError: Tells the delegate that the data task finished transferring the data.
 +
 +
If you don’t need the features provided by a delegate, you can use this API without providing one by passing nil when you create a session.
 +
 +
=== Example code ===
 +
 +
<syntaxhighlight lang=pascal>
 +
unit Unit1;
 +
 +
{$mode objfpc}{$H+}
 +
{$modeswitch objectivec1}
 +
 +
interface
 +
 +
uses
 +
  Forms,      // for the main form
 +
  Dialogs,    // for ShowMessage
 +
  StdCtrls,  // for the button
 +
  SysUtils,  // for IntToStr()
 +
  CocoaAll,  // for NSData and other Cocoa types
 +
  CocoaUtils, Classes; // for NSStringString
 +
 +
type
 +
  // redefine version from packages/cocoaint/src/foundation/NSURLSession.inc
 +
  NSURLSession = objcclass external (NSObject)
 +
  public
 +
    class function sessionWithConfiguration(configuration: NSURLSessionConfiguration): NSURLSession;
 +
      message 'sessionWithConfiguration:';
 +
    class function sessionWithConfiguration_delegate_delegateQueue(configuration: NSURLSessionConfiguration; delegate: NSURLSessionDelegateProtocol; queue: NSOperationQueue): NSURLSession;
 +
      message 'sessionWithConfiguration:delegate:delegateQueue:';
 +
    function dataTaskWithURL(url: NSURL): NSURLSessionDataTask;
 +
      message 'dataTaskWithURL:';
 +
  end;
 +
 +
  { TMyDelegate }
 +
  TMyDelegate = objcclass(NSObject, NSURLSessionDelegateProtocol)
 +
  private
 +
 +
  public
 +
    procedure URLSession_dataTask_didReceiveData (session: NSURLSession; dataTask: NSURLSessionDataTask; data: NSData);
 +
      message 'URLSession:dataTask:didReceiveData:';
 +
    procedure URLSession_task_didCompleteWithError (session: NSURLSession; task: NSURLSessionTask; error: NSError);
 +
      message 'URLSession:task:didCompleteWithError:';
 +
  end;
 +
 +
  { TForm1 }
 +
 +
  TForm1 = class(TForm)
 +
    Button1: TButton;
 +
    procedure Button1Click(Sender: TObject);
 +
  private
 +
 +
  public
 +
 +
  end;
 +
 +
var
 +
  Form1: TForm1;
 +
  myCache: NSURLcache;
 +
  responseData: NSMutableData;
 +
  queue: NSOperationQueue;
 +
  sessionDelegate: TMyDelegate;
 +
  webData: NSString;
 +
  webError: String;
 +
  ThreadDidFinish: PRTLEvent;
 +
 +
implementation
 +
 +
{$R *.lfm}
 +
 +
{ TForm1 }
 +
 +
//{$DEFINE DEBUG}
 +
 +
procedure TMyDelegate.URLSession_dataTask_didReceiveData(session: NSURLSession; dataTask: NSURLSessionDataTask; data: NSData);
 +
begin
 +
  {$IFDEF DEBUG}
 +
  NSLog(NSStr('didReceiveData'));
 +
  {$ENDIF}
 +
 +
  // Append the new data to the response variable
 +
  responseData.appendData(data);
 +
end;
 +
 +
procedure TMyDelegate.URLSession_task_didCompleteWithError(session: NSURLSession; task: NSURLSessionTask; error: NSError);
 +
begin
 +
  {$IFDEF DEBUG}
 +
  NSLog(NSStr('didCompleteWithError'));
 +
  NSLog(NSString.alloc.initWithData(responseData,NSUTF8StringEncoding));
 +
  {$ENDIF}
 +
 +
  // Is there an error?
 +
  if(responseData.length = 0) then
 +
    begin
 +
      NSLog(NSStr('Error %@'), error.description);
 +
      webError := 'Error retrieving: ' + NSStringToString(error.userInfo.valueForKey(NSErrorFailingUrlStringKey))
 +
        + LineEnding + LineEnding + 'Reason: ' + NSStringToString(error.localizedDescription);
 +
    end
 +
  else
 +
    begin
 +
      webError := '';
 +
      webData := NSString.alloc.initWithData(responseData,NSUTF8StringEncoding);
 +
    end;
 +
 +
  // notify main thread that data retrieval thread has finished
 +
  RTLEventSetEvent(ThreadDidFinish);
 +
end;
 +
 +
procedure TForm1.Button1Click(Sender: TObject);
 +
var
 +
  urlSessionConfig: NSURLSessionConfiguration = Nil;
 +
  cachePath: NSString = Nil;
 +
  urlSession: NSURLSession = Nil;
 +
  URL: NSURL = Nil;
 +
begin
 +
  // create event to synchronise data retrieval background thread
 +
  // with the GUI main thread
 +
  ThreadDidFinish := RTLEventCreate;
 +
 +
  // create default url session config
 +
  urlSessionConfig := NSURLSessionConfiguration.defaultSessionConfiguration;
 +
 +
  // create connection delegate
 +
  sessionDelegate := TMyDelegate.alloc.init;
 +
 +
  // create responseData
 +
  responseData := NSMutableData.alloc.init;
 +
 +
  // configure caching behavior for the default session
 +
  cachePath := NSTemporaryDirectory.stringByAppendingPathComponent(NSStr('/nsurlsessiondemo.cache'));
 +
 +
  {$IFDEF DEBUG}
 +
  NSLog(NSStr('Cache path: %@'), cachePath);
 +
  {$ENDIF}
 +
 +
  myCache := NSURLCache.alloc.initWithMemoryCapacity_diskCapacity_diskPath(16384, 268435456, cachePath);
 +
  urlSessionConfig.setURLCache(myCache);
 +
 +
  // set cache policy
 +
  {$IFDEF DEBUG}
 +
  urlSessionConfig.setRequestCachePolicy(NSURLRequestReloadIgnoringLocalCacheData);
 +
  {$ELSE}
 +
  urlSessionConfig.setRequestCachePolicy(NSURLRequestUseProtocolCachePolicy);
 +
  {$ENDIF}
 +
 +
  // create a session for configuration
 +
  urlSession := NSURLSession.sessionWithConfiguration_delegate_delegateQueue(urlSessionConfig, sessionDelegate, queue);
 +
 +
  // create NSURL
 +
  URL := NSURL.URLWithString(NSSTR(PAnsiChar('https://sentinel.sentry.org/')));
 +
  if(Url = Nil) then
 +
      ShowMessage('NSURL.URLWithString failed!');
 +
 +
  // setup and execute data task
 +
  urlSession.dataTaskWithURL(URL).resume;
 +
 +
  // wait for data retrieval thread to finish
 +
  RTLEventWaitFor(ThreadDidFinish);
 +
 +
  // Show result
 +
  if(webError <> '') then
 +
    ShowMessage(webError)
 +
  else
 +
    ShowMessage(NSStringToString(webData));
 +
 +
  // housekeeping
 +
  RTLeventdestroy(ThreadDidFinish);
 +
end;
 +
 +
Finalization
 +
  // housekeeping
 +
  myCache.release;
 +
end.
 +
</syntaxhighlight>
 +
 +
===== Compilation note =====
 +
 +
See the previous Compilation note [[#Compilation note|above]].
 +
 +
== See also ==
 +
 +
* [[macOS NSURLConnection]] deprecated in favour of [[macOS NSURLSession]].
 +
 +
== External links ==
 +
 +
* [https://developer.apple.com/documentation/foundation/nsurl?language=objc Apple: NSURL].
 +
* [https://developer.apple.com/documentation/foundation/nsurlsession Apple: NSURLSession].
 +
* [https://developer.apple.com/documentation/foundation/nsurlcache Apple: NSURLCache].
 +
* [https://developer.apple.com/documentation/foundation/nsurlsessionconfiguration Apple: NSURLSessionConfiguration].
 +
* [https://developer.apple.com/documentation/foundation/nsurlresponse Apple: NSURLResponse].
 +
* [https://developer.apple.com/documentation/foundation/nshttpurlresponse Apple: NSHTTPURLResponse].

Latest revision as of 22:21, 2 December 2020

English (en)

macOSlogo.png

This article applies to macOS only.

See also: Multiplatform Programming Guide


Overview

The NSURLSession class and related classes provide an API for downloading content via HTTP. The downloading is performed asynchronously, so your application can remain responsive and handle incoming data or errors as they arrive. This class replaces the macOS NSURLConnection class which was deprecated by Apple in macOS 10.11 (El Capitan) in 2015. NSURLSession is available from macOS 10.9 (Mavericks) onwards.

The NSURLSession API is highly asynchronous. If you use the default, system-provided delegate, you must provide a completion handler block that returns data to your application when a transfer finishes successfully or with an error. Alternatively, if you provide your own custom delegate objects, the task objects call those delegates’ methods with data as it is received from the server (or, for file downloads, when the transfer is complete). The NSURLSession API provides status and progress properties, in addition to delivering this information to delegates. It supports cancelling, resuming, and suspending tasks, and it provides the ability to resume suspended, cancelled, or failed downloads where they left off.

The behaviour of the tasks in a session depends on three things:

  1. the type of session (determined by the type of configuration object used to create it),
  2. the type of task, and
  3. whether the application was in the foreground when the task was created.

Types of sessions

The NSURLSession API supports three types of sessions, as determined by the type of configuration object used to create the session:

  1. Default sessions behave similarly to other Foundation methods for downloading URLs. They use a persistent disk-based cache and store credentials in the user’s keychain. A default session configuration object results in a session that behaves like an NSURLConnection object in its standard configuration. Altering a session configuration obtained through the defaultSessionConfiguration method does not change the default session configuration of which it is a copy.
  2. Ephemeral sessions do not store any data to disk; all caches, credential stores, and so on are kept in RAM and tied to the session. Thus, when your application invalidates the session, they are purged automatically. Ephemeral sessions are therefore ideal if you need to implement private browsing.
  3. Background sessions are similar to default sessions, except that a separate process handles all data transfers. Background sessions have some additional limitations:
    1. The session must provide a delegate for uploads and downloads.
    2. Only HTTP and HTTPS protocols are supported.
    3. Only upload and download tasks are supported (no data tasks).
    4. Redirects are always followed.
    5. If the background transfer is initiated while the app is in the background, the configuration object’s discretionary property is treated as being true.
    6. Background configurations cannot be reused (ie you cannot use two background session configurations using the same configuration identifier).

Types of Tasks

An NSURLSession supports four types of tasks:

  • data tasks,
  • download tasks,
  • upload tasks, and
  • webSocket tasks.

Data tasks send and receive data using NSData objects. Data tasks are intended for short, often interactive requests to a server. Data tasks can return data to your application one piece at a time after each piece of data is received, or all at once through a completion handler. As data tasks do not store the data to a file, they are not supported in background sessions.

Download tasks retrieve data in the form of a file, and support background downloads.

Upload tasks send data (usually in the form of a file), and support background uploads.

Web socket tasks exchange messages over TCP and TLS, using the WebSocket protocol defined in RFC 6455.

Asynchronicity

The NSURLSession API is highly asynchronous. It returns data to your application in one of two ways, depending on the methods you call:

  • by calling a completion handler block when a transfer finishes successfully or with an error; or
  • by calling methods on the session’s delegate as data arrives and when the transfer is complete.

In addition to delivering this information to delegates, the NSURLSession provides status and progress properties that you can query if you need to make programmatic decisions based on the current state of the task (with the caveat that its state can change at any time).

Protocol support

An NSURLSession natively supports the data, file, ftp, http, and https URL schemes, with transparent support for proxy servers and SOCKS gateways, as configured in the user’s system preferences. It supports HTTP/1.1 and HTTP/2 protocols. HTTP/2, described in RFC 7540, requires a server that supports Application-Layer Protocol Negotiation (ALPN).

Creating a session

The NSURLSession API provides a wide range of configuration options:

  • Private storage support for caches, cookies, credentials, and protocols in a way that is specific to a single session.
  • Authentication, tied to a specific request (task) or group of requests (session).
  • File uploads and downloads by URL, which encourages separation of the data (the file’s contents) from the metadata (the URL and settings).
  • Configuration of the maximum number of connections per host.
  • Per-resource timeouts that are triggered if an entire resource cannot be downloaded in a certain amount of time.
  • Minimum and maximum TLS version support Custom proxy dictionaries.
  • Control over cookie policies.
  • Control over HTTP pipelining behaviour.

When you instantiate a session object, you specify the following:

  • A configuration object that governs the behaviour of that session and the tasks within it
  • Optionally, a delegate object to process incoming data as it is received and handle other events specific to the session and the tasks within it, such as server authentication, determining whether a resource load request should be converted into a download, and so on.
  • If you do not provide a delegate, the NSURLSession object uses a system-provided delegate. In this way, you can readily use NSURLSession in place of existing code that uses the sendAsynchronousRequest:queue:completionHandler: convenience method on NSURLSession.

As these settings are contained in a separate configuration object, you can reuse commonly used settings in other sessions.

Retrieving data using system-provided delegates

This simple demonstration shows how to use NSURLSession and related classes to download and display a web page using NSURLSession as a drop-in replacement for the NSURLConnection sendAsynchronousRequest:queue:completionHandler: method. Using this method, you need to provide only two pieces of code in your application:

  1. code to create a configuration object and a session based on that object; and
  2. code to implement a completion handler routine to do something with the data after it has been fully received.

Example code

unit Unit1;

{$mode objfpc}{$H+}
{$modeswitch objectivec1}
{$modeswitch cblocks}

interface

uses
  Forms,      // for the main form
  Dialogs,    // for ShowMessage
  StdCtrls,   // for the button
  SysUtils,   // for IntToStr()
  CocoaAll,   // for NSData and other Cocoa types
  CocoaUtils; // for NSStringString

type
  // setup cBlock for completion handler
  tblock = reference to procedure(data: NSData; response: NSURLResponse; connectionError: NSError); cdecl; cblock;

  // redefine version from packages/cocoaint/src/foundation/NSURLSession.inc
  NSURLSession = objcclass external (NSObject)
  public
    class function sessionWithConfiguration(configuration: NSURLSessionConfiguration): NSURLSession; 
      message 'sessionWithConfiguration:';
  end;

  NSURLSessionAsynchronousConvenience = objccategory external (NSURLSession)
    function dataTaskWithURL_completionHandler(url: NSURL; completionHandler: tBlock): NSURLSessionDataTask; 
      message 'dataTaskWithURL:completionHandler:';
  end;

  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private

  public

  end;

var
  Form1: TForm1;
  myCache: NSURLcache;
  webData: String;
  webResponse: String;
  webHTML: String;
  webStatusCode: Integer;
  webError: String;
  webErrorReason: String;
  didFinish: PRTLEvent;

implementation

{$R *.lfm}

{ TForm1 }

//{$DEFINE DEBUG}

// Completion handler: Executed after URL has been retrieved or retrieval fails
procedure myCompletionHandler(data: NSData; response: NSURLResponse; connectionError: NSError);
var
  httpResponse: NSHTTPURLResponse;
begin
  {$IFDEF DEBUG}
  NSLog(NSStr('entering completion handler'));
  {$ENDIF}

  // if no error
  if((data.Length > 0) and (connectionError = Nil)) then
    begin
      {$IFDEF DEBUG}
      NSLog(data.description);
      NSLog(response.description);
      NSLog(NSString.alloc.initWithData(data,NSUTF8StringEncoding));
      {$ENDIF}
      webData     :=  NSStringToString(data.description);
      {$IFDEF DEBUG}
      NSLog(NSStr('Web data' + webData));
      {$ENDIF}

      // The NSHTTPURLResponse class is a subclass of NSURLResponse
      // so we can cast an NSURLResponse as an NSHTTPURLResponse
      httpResponse := NSHTTPURLResponse(response);

      // Extract status code from response header
      {$IFDEF DEBUG}
      NSLog(NSStr(IntToStr(httpResponse.statusCode)));
      {$ENDIF}

      webStatusCode :=  httpResponse.statusCode;
      webResponse   :=  NSStringToString(response.description);
      webHTML       :=  NSSTringToString(NSString.alloc.initWithData(data,NSUTF8StringEncoding));
    end
  // o/w return error
  else
    begin
      {$IFDEF DEBUG}
      NSLog(NSStr('Error %@'), connectionError.userInfo);
      {$ENDIF}

      webError := 'Error description: ' + LineEnding +  NSStringToString(connectionError.description);
      webErrorReason := 'Error retrieving: ' + NSStringToString(connectionError.userInfo.valueForKey(NSErrorFailingUrlStringKey))
        + LineEnding + LineEnding + 'Reason: ' + NSStringToString(connectionError.localizedDescription);
    end;

  // notify main thread that completion handler thread has finished
  RTLEventSetEvent(didFinish);

  {$IFDEF DEBUG}
  NSLog(NSStr('leaving completion handler'));
  {$ENDIF}
end;

// Retrieve web page
procedure TForm1.Button1Click(Sender: TObject);
var
  urlSessionConfig: NSURLSessionConfiguration;
  cachePath: NSString;
  urlSession: NSURLSession;
  URL: NSURL;
begin
  // create event to synchronise completion handler background thread
  // with the GUI main thread
  didFinish := RTLEventCreate;  

  // create default url session config
  urlSessionConfig := NSURLSessionConfiguration.defaultSessionConfiguration;

  // configure caching behavior for the default session
  cachePath := NSTemporaryDirectory.stringByAppendingPathComponent(NSStr('/nsurlsessiondemo.cache'));

  {$IFDEF DEBUG}
  NSLog(NSStr('Cache path: %@'), cachePath);
  {$ENDIF}

  myCache := NSURLCache.alloc.initWithMemoryCapacity_diskCapacity_diskPath(16384, 268435456, cachePath);
  urlSessionConfig.setURLCache(myCache);

  // set cache policy
  {$IFDEF DEBUG} 
  urlSessionConfig.setRequestCachePolicy(NSURLRequestReloadIgnoringLocalCacheData);
  {$ELSE}
  urlSessionConfig.setRequestCachePolicy(NSURLRequestUseProtocolCachePolicy);
  {$ENDIF}

  // create a session for configuration
  urlSession := NSURLSession.sessionWithConfiguration(urlSessionConfig);

  // create NSURL
  URL := NSURL.URLWithString(NSSTR(PAnsiChar('https://sentinel.sentry.org/')));
  if(Url = Nil) then
      ShowMessage('NSURL.URLWithString failed!');

  // setup and execute (resume) data task
  urlSession.dataTaskWithURL_completionHandler(URL, @myCompletionHandler).resume;

  // wait for completion handler to finish
  RTLEventWaitFor(didFinish); 

  // display results
  if(webErrorReason <> '') then
    begin
      ShowMessage(webError);
      ShowMessage(webErrorReason);
    end
  else
    begin
      ShowMessage('HTTP status code: ' + IntToStr(webStatusCode) + LineEnding
        + LineEnding + 'Raw data: ' + LineEnding + webData);
      ShowMessage('Response: ' + LineEnding + LineEnding + webResponse);
      ShowMessage('Web page: ' + LineEnding + LineEnding + webHTML);
    end;

  // housekeeping
  RTLeventdestroy(didFinish);
end;

Finalization
  // housekeeping
  myCache.release;
end.
Compilation note

To compile the above code successfully you are going to have to add the missing initWithData function to the NSString class by editing /usr/local/share/fpcsrc/fpc-[3.0.4|3.2.0|3.3.1]/packages/cocoaint/src/foundation/NSString.inc to add the missing (highlighted) function as follows:

--- NSString.inc        (revision 45778)
+++ NSString.inc        (working copy)
@@ -105,6 +105,7 @@
     function characterAtIndex (index: NSUInteger): unichar; message 'characterAtIndex:';
     function init: instancetype; message 'init'; { NS_DESIGNATED_INITIALIZER }
     function initWithCoder (aDecoder: NSCoder): instancetype; message 'initWithCoder:'; { NS_DESIGNATED_INITIALIZER }
+    function initWithData(data: NSData; encoding: NSStringEncoding) : instancetype; message 'initWithData:encoding:';
 
     { Adopted protocols }
     function copyWithZone (zone: NSZonePtr): id; message 'copyWithZone:';

and then recompile the FPC source. This has been tested with FPC 3.0.4, FPC 3.2.0 and FPC 3.3.1. Note that for FPC 3.0.4 you need to replace "instancetype" in the highlighted line with "id"

I use the following script (for FPC 3.3.1; substitute your FPC version numbers as appropriate) to recompile FPC:

#!/bin/sh
cd /usr/local/share/fpcsrc/fpc-3.3.1/
make clean all FPC=/usr/local/lib/fpc/3.3.1/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64 OPT="-XR/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/"
make install FPC=/usr/local/lib/fpc/3.3.1/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64
  • Note 1: The highlighted line(s) above should be all on one line.
  • Note 2: You will almost certainly have to use sudo to execute that script successfully or face permissions problems.

Retrieving data using a custom delegate

When using a custom delegate to retrieve data, the delegate must implement at least the following methods:

  • URLSession:dataTask:didReceiveData: Tells the delegate that the data task has received some of the expected data.
  • URLSession:task:didCompleteWithError: Tells the delegate that the data task finished transferring the data.

If you don’t need the features provided by a delegate, you can use this API without providing one by passing nil when you create a session.

Example code

unit Unit1;

{$mode objfpc}{$H+}
{$modeswitch objectivec1}

interface

uses
  Forms,      // for the main form
  Dialogs,    // for ShowMessage
  StdCtrls,   // for the button
  SysUtils,   // for IntToStr()
  CocoaAll,   // for NSData and other Cocoa types
  CocoaUtils, Classes; // for NSStringString

type
  // redefine version from packages/cocoaint/src/foundation/NSURLSession.inc
  NSURLSession = objcclass external (NSObject)
  public
    class function sessionWithConfiguration(configuration: NSURLSessionConfiguration): NSURLSession;
      message 'sessionWithConfiguration:';
    class function sessionWithConfiguration_delegate_delegateQueue(configuration: NSURLSessionConfiguration; delegate: NSURLSessionDelegateProtocol; queue: NSOperationQueue): NSURLSession;
      message 'sessionWithConfiguration:delegate:delegateQueue:';
    function dataTaskWithURL(url: NSURL): NSURLSessionDataTask;
      message 'dataTaskWithURL:';
  end;

  { TMyDelegate }
  TMyDelegate = objcclass(NSObject, NSURLSessionDelegateProtocol)
  private

  public
    procedure URLSession_dataTask_didReceiveData (session: NSURLSession; dataTask: NSURLSessionDataTask; data: NSData);
      message 'URLSession:dataTask:didReceiveData:';
    procedure URLSession_task_didCompleteWithError (session: NSURLSession; task: NSURLSessionTask; error: NSError);
      message 'URLSession:task:didCompleteWithError:';
  end;

  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private

  public

  end;

var
  Form1: TForm1;
  myCache: NSURLcache;
  responseData: NSMutableData;
  queue: NSOperationQueue;
  sessionDelegate: TMyDelegate;
  webData: NSString;
  webError: String;
  ThreadDidFinish: PRTLEvent;

implementation

{$R *.lfm}

{ TForm1 }

//{$DEFINE DEBUG}

procedure TMyDelegate.URLSession_dataTask_didReceiveData(session: NSURLSession; dataTask: NSURLSessionDataTask; data: NSData);
begin
  {$IFDEF DEBUG}
  NSLog(NSStr('didReceiveData'));
  {$ENDIF}

  // Append the new data to the response variable
  responseData.appendData(data);
end;

procedure TMyDelegate.URLSession_task_didCompleteWithError(session: NSURLSession; task: NSURLSessionTask; error: NSError);
begin
  {$IFDEF DEBUG}
  NSLog(NSStr('didCompleteWithError'));
  NSLog(NSString.alloc.initWithData(responseData,NSUTF8StringEncoding));
  {$ENDIF}

  // Is there an error?
  if(responseData.length = 0) then
     begin
       NSLog(NSStr('Error %@'), error.description);
       webError := 'Error retrieving: ' + NSStringToString(error.userInfo.valueForKey(NSErrorFailingUrlStringKey))
        + LineEnding + LineEnding + 'Reason: ' + NSStringToString(error.localizedDescription);
     end
  else
    begin
      webError := '';
      webData := NSString.alloc.initWithData(responseData,NSUTF8StringEncoding);
    end;

  // notify main thread that data retrieval thread has finished
  RTLEventSetEvent(ThreadDidFinish);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  urlSessionConfig: NSURLSessionConfiguration = Nil;
  cachePath: NSString = Nil;
  urlSession: NSURLSession = Nil;
  URL: NSURL = Nil;
begin
  // create event to synchronise data retrieval background thread
  // with the GUI main thread
  ThreadDidFinish := RTLEventCreate;

  // create default url session config
  urlSessionConfig := NSURLSessionConfiguration.defaultSessionConfiguration;

  // create connection delegate
  sessionDelegate := TMyDelegate.alloc.init;

  // create responseData
  responseData := NSMutableData.alloc.init;

  // configure caching behavior for the default session
  cachePath := NSTemporaryDirectory.stringByAppendingPathComponent(NSStr('/nsurlsessiondemo.cache'));

  {$IFDEF DEBUG}
  NSLog(NSStr('Cache path: %@'), cachePath);
  {$ENDIF}

  myCache := NSURLCache.alloc.initWithMemoryCapacity_diskCapacity_diskPath(16384, 268435456, cachePath);
  urlSessionConfig.setURLCache(myCache);

  // set cache policy
  {$IFDEF DEBUG}
  urlSessionConfig.setRequestCachePolicy(NSURLRequestReloadIgnoringLocalCacheData);
  {$ELSE}
  urlSessionConfig.setRequestCachePolicy(NSURLRequestUseProtocolCachePolicy);
  {$ENDIF}

  // create a session for configuration
  urlSession := NSURLSession.sessionWithConfiguration_delegate_delegateQueue(urlSessionConfig, sessionDelegate, queue);

  // create NSURL
  URL := NSURL.URLWithString(NSSTR(PAnsiChar('https://sentinel.sentry.org/')));
  if(Url = Nil) then
      ShowMessage('NSURL.URLWithString failed!');

  // setup and execute data task
  urlSession.dataTaskWithURL(URL).resume;

  // wait for data retrieval thread to finish
  RTLEventWaitFor(ThreadDidFinish);

  // Show result
  if(webError <> '') then
     ShowMessage(webError)
  else
     ShowMessage(NSStringToString(webData));

  // housekeeping
  RTLeventdestroy(ThreadDidFinish);
end;

Finalization
  // housekeeping
  myCache.release;
end.
Compilation note

See the previous Compilation note above.

See also

External links