Sign in Join
Wiki copytemporary

macOS NSURLSession: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: macOS NSURLSession

OldNewLine
1+## Overview
2+
3+The NSURLSession class and related classes provide an API for downloading content via HTTP and HTTPS. 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.
4+
5+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.
6+
7+The behaviour of the tasks in a session depends on three things:
8+
9+1. the type of session (determined by the type of configuration object used to create it),
10+2. the type of task, and
11+3. whether the application was in the foreground when the task was created.
12+
13+### Types of sessions
14+
15+The NSURLSession API supports three types of sessions, as determined by the type of configuration object used to create the session:
16+
17+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.
18+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.
19+3. Background sessions are similar to default sessions, except that a separate process handles all data transfers. Background sessions have some additional limitations:
20+ 1. The session must provide a delegate for uploads and downloads.
21+ 2. Only HTTP and HTTPS protocols are supported.
22+ 3. Only upload and download tasks are supported (no data tasks).
23+ 4. Redirects are always followed.
24+ 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.
25+ 6. Background configurations cannot be reused (ie you cannot use two background session configurations using the same configuration identifier).
26+
27+### Types of Tasks
28+
29+An NSURLSession supports four types of tasks:
30+
31+- data tasks,
32+- download tasks,
33+- upload tasks, and
34+- webSocket tasks.
35+
36+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.
37+
38+Download tasks retrieve data in the form of a file, and support background downloads.
39+
40+Upload tasks send data (usually in the form of a file), and support background uploads.
41+
42+Web socket tasks exchange messages over TCP and TLS, using the WebSocket protocol defined in [RFC 6455](https://tools.ietf.org/html/rfc6455).
43+
44+### Asynchronicity
45+
46+The NSURLSession API is highly asynchronous. It returns data to your application in one of two ways, depending on the methods you call:
47+
48+- by calling a completion handler block when a transfer finishes successfully or with an error; or
49+- by calling methods on the session’s delegate as data arrives and when the transfer is complete.
50+
51+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).
52+
53+### Protocol support
54+
55+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](https://tools.ietf.org/html/rfc7540), requires a server that supports Application-Layer Protocol Negotiation (ALPN). macOS 10.11 (El Capitan) and later use App Transport Security (ATS) for all HTTP connections made with NSURLSession. ATS requires that HTTP connections use HTTPS ([RFC 2818](https://tools.ietf.org/html/rfc2818)).
56+
57+### Creating a session
58+
59+The NSURLSession API provides a wide range of configuration options:
60+
61+- Private storage support for caches, cookies, credentials, and protocols in a way that is specific to a single session.
62+- Authentication, tied to a specific request (task) or group of requests (session).
63+- File uploads and downloads by URL, which encourages separation of the data (the file’s contents) from the metadata (the URL and settings).
64+- Configuration of the maximum number of connections per host.
65+- Per-resource timeouts that are triggered if an entire resource cannot be downloaded in a certain amount of time.
66+- Minimum and maximum TLS version support Custom proxy dictionaries.
67+- Control over cookie policies.
68+- Control over HTTP pipelining behaviour.
69+
70+When you instantiate a session object, you specify the following:
71+
72+- A configuration object that governs the behaviour of that session and the tasks within it
73+- 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.
74+- 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.
75+
76+As these settings are contained in a separate configuration object, you can reuse commonly used settings in a configuration object in other sessions provided they are not background sessions. When you create a session, the session copies the configuration object and, as a result, modifications of the configuration object only affect new sessions and not existing sessions. However, you cannot reuse background session configuration objects because the behaviour of two background session objects sharing the same identifier is undefined.
77+
78+### Caching policies
79+
80+Network caching reduces the number of requests that need to be made to the server, and improve the experience of using an application offline or under slow network conditions. An NSURLRequest instance specifies how the local cache is used by setting the cache policy to one of the **NSURLRequestCachePolicy** values. The default cache policy for an NSURLRequest instance is **NSURLRequestUseProtocolCachePolicy** which is protocol specific and is defined as being the best conforming policy for the protocol.
81+
82+There are a number of different NSURLRequest caching policies from which to choose:
83+
84+- **NSURLRequestUseProtocolCachePolicy** Use the caching logic defined in the protocol implementation, if any, for a particular URL load request.
85+- **NSURLRequestReloadIgnoringLocalCacheData** The URL load should be loaded only from the originating source.
86+- **NSURLRequestReloadIgnoringLocalAndRemoteCacheData** Ignore local cache data, and instruct proxies and other intermediates to disregard their caches so far as the protocol allows.
87+- **NSURLRequestReturnCacheDataElseLoad** Use existing cache data, regardless or age or expiration date, loading from originating source only if there is no cached data.
88+- **NSURLRequestReturnCacheDataDontLoad** Use existing cache data, regardless or age or expiration date, and fail if no cached data is available.
89+- **NSURLRequestReloadRevalidatingCacheData** Use cache data if the origin source can validate it; otherwise, load from the origin.
90+
91+The default cache policy is **NSURLRequestUseProtocolCachePolicy** and is almost always the best choice rather than implementing your own caching or changing the cache policy of the request. When a server responds to an HTTP request, the response includes information about how long and under what conditions the response will be valid. However, for debugging I always prefer **NSURLRequestReloadIgnoringLocalCacheData** ro ensure the data isn not coming from the local cache and that a request is actually made whether it is fulfilled by the origin server or an intermediate proxy.
92+
93+## Retrieving data using system-provided delegates
94+
95+The NSURLSession object does not need to have a delegate. If no delegate is assigned, a system-provided delegate is used, and you must provide a completion handler callback to obtain the data.
96+
97+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|NSURLConnection sendAsynchronousRequest:queue:completionHandler:]] method. Using this method, you need to provide only two pieces of code in your application:
98+
99+1. code to create a configuration object and a session based on that object; and
100+2. code to implement a completion handler routine to do something with the data after it has been fully received.
101+
102+### Example code
103+
104+``` pascal
105+unit Unit1;
106+
107+{$mode objfpc}{$H+}
108+{$modeswitch objectivec1}
109+{$modeswitch cblocks}
110+
111+interface
112+
113+uses
114+ Forms, // for the main form
115+ Dialogs, // for ShowMessage
116+ StdCtrls, // for the button
117+ SysUtils, // for IntToStr()
118+ CocoaAll, // for NSData and other Cocoa types
119+ CocoaUtils; // for NSStringString
120+
121+type
122+ // setup cBlock for completion handler
123+ tblock = reference to procedure(data: NSData; response: NSURLResponse; connectionError: NSError); cdecl; cblock;
124+
125+ // redefine version from packages/cocoaint/src/foundation/NSURLSession.inc
126+ NSURLSession = objcclass external (NSObject)
127+ public
128+ class function sessionWithConfiguration(configuration: NSURLSessionConfiguration): NSURLSession; message 'sessionWithConfiguration:';
129+ end;
130+
131+ NSURLSessionAsynchronousConvenience = objccategory external (NSURLSession)
132+ function dataTaskWithURL_completionHandler(url: NSURL; completionHandler: tBlock): NSURLSessionDataTask; message 'dataTaskWithURL:completionHandler:';
133+ end;
134+
135+ { TForm1 }
136+
137+ TForm1 = class(TForm)
138+ Button1: TButton;
139+ procedure Button1Click(Sender: TObject);
140+ private
141+
142+ public
143+
144+ end;
145+
146+var
147+ Form1: TForm1;
148+ myCache: NSURLcache;
149+ webData: String;
150+ webResponse: String;
151+ webHTML: String;
152+ webStatusCode: Integer;
153+ webError: String;
154+ webErrorReason: String;
155+ didFinish: PRTLEvent;
156+
157+implementation
158+
159+{$R *.lfm}
160+
161+{ TForm1 }
162+
163+{$DEFINE DEBUG}
164+
165+// Completion handler: Executed after URL has been retrieved or retrieval fails
166+procedure myCompletionHandler(data: NSData; response: NSURLResponse; connectionError: NSError);
167+var
168+ httpResponse: NSHTTPURLResponse;
169+begin
170+ {$IFDEF DEBUG}
171+ NSLog(NSStr('Completion handler called'));
172+
173+ if (NSThread.currentThread.isMainThread) then
174+ NSLog(NSStr('In main thread--completion handler'))
175+ else
176+ NSLog(NSStr('Not in main thread--completion handler'));
177+ {$ENDIF}
178+
179+ // if no error
180+ if((data.Length > 0) and (connectionError = Nil)) then
181+ begin
182+ {$IFDEF DEBUG}
183+ NSLog(NSStr('Data desciption: %@'),data.description);
184+ NSLog(NSStr('Response description: %@'),response.description);
185+ NSLog(NSStr('Data: %@'),NSString.alloc.initWithData_encoding(data,NSASCIIStringEncoding).autorelease);
186+ {$ENDIF}
187+ webData := NSStringToString(data.description);
188+ {$IFDEF DEBUG}
189+ NSLog(NSStr('Web data' + webData));
190+ {$ENDIF}
191+ // The NSHTTPURLResponse class is a subclass of NSURLResponse
192+ // so we can cast an NSURLResponse as an NSHTTPURLResponse
193+ httpResponse := NSHTTPURLResponse(response);
194+ {$IFDEF DEBUG}
195+ // Extract status code from response header
196+ NSLog(NSStr('HTTP status code: %@'),NSStr(IntToStr(httpResponse.statusCode)));
197+ {$ENDIF}
198+ webStatusCode := httpResponse.statusCode;
199+ webResponse := NSStringToString(response.description);
200+ webHTML := NSSTringToString(NSString.alloc.initWithData_encoding(data,NSASCIIStringEncoding));
201+ end
202+ // o/w return error
203+ else
204+ begin
205+ {$IFDEF DEBUG}
206+ NSLog(NSStr('Error %@'), connectionError.userInfo);
207+ {$ENDIF}
208+ webError := 'Error description: ' + LineEnding + NSStringToString(connectionError.description);
209+ webErrorReason := 'Error retrieving: ' + NSStringToString(connectionError.userInfo.valueForKey(NSErrorFailingUrlStringKey))
210+ + LineEnding + LineEnding + 'Reason: ' + NSStringToString(connectionError.localizedDescription);
211+ end;
212+
213+ // notify main thread that completion handler thread has finished
214+ RTLEventSetEvent(didFinish);
215+
216+ {$IFDEF DEBUG}
217+ NSLog(NSStr('leaving handler'));
218+ {$ENDIF}
219+end;
220+
221+procedure TForm1.Button1Click(Sender: TObject);
222+var
223+ urlSessionConfig: NSURLSessionConfiguration = Nil;
224+ cachePath: NSString = Nil;
225+ urlSession: NSURLSession = Nil;
226+ URL: NSURL = Nil;
227+begin
228+ // create event to synchronise completion handler background thread
229+ // with the GUI main thread
230+ didFinish := RTLEventCreate;
231+
232+ // create default url session config
233+ urlSessionConfig := NSURLSessionConfiguration.defaultSessionConfiguration;
234+
235+ // configure caching behavior for the default session
236+ cachePath := NSTemporaryDirectory.stringByAppendingPathComponent(NSStr('/nsurlsessiondemo.cache'));
237+
238+ {$IFDEF DEBUG}
239+ NSLog(NSStr('Cache path: %@'), cachePath);
240+ {$ENDIF}
241+
242+ myCache := NSURLCache.alloc.initWithMemoryCapacity_diskCapacity_diskPath(16384, 268435456, cachePath);
243+ urlSessionConfig.setURLCache(myCache);
244+
245+ // set cache policy
246+ {$IFDEF DEBUG}
247+ urlSessionConfig.setRequestCachePolicy(NSURLRequestReloadIgnoringLocalCacheData);
248+ {$ELSE}
249+ urlSessionConfig.setRequestCachePolicy(NSURLRequestUseProtocolCachePolicy);
250+ {$ENDIF}
251+
252+ // create a session for configuration
253+ urlSession := NSURLSession.sessionWithConfiguration(urlSessionConfig);
254+
255+ // create NSURL
256+ URL := NSURL.URLWithString(NSSTR(PAnsiChar('https://sentinel.sentry.org/')));
257+ if(Url = Nil) then
258+ ShowMessage('NSURL.URLWithString failed!');
259+
260+ // setup and execute data task
261+ urlSession.dataTaskWithURL_completionHandler(URL, @myCompletionHandler).resume;
262+
263+ // wait for completion handler to finish
264+ RTLEventWaitFor(didFinish);
265+
266+ // display results
267+ if(webErrorReason <> '') then
268+ begin
269+ ShowMessage(webError);
270+ ShowMessage(webErrorReason);
271+ end
272+ else
273+ begin
274+ ShowMessage('HTTP status code: ' + IntToStr(webStatusCode) + LineEnding
275+ + LineEnding + 'Raw data: ' + LineEnding + webData);
276+ ShowMessage('Response: ' + LineEnding + LineEnding + webResponse);
277+ ShowMessage('Web page: ' + LineEnding + LineEnding + webHTML);
278+ end;
279+
280+ // housekeeping
281+ RTLeventdestroy(didFinish);
282+ myCache.release;
283+end;
284+
285+end.
286+```
287+
288+Full project source code is available from [SourceForge](https://sourceforge.net/p/lazarus-wiki-projects/code/ci/master/tree/laz_nsurlsession/).
289+
290+##### Compilation note
291+
292+To compile the above code successfully you are going to have to add the missing *initWithData_encoding* 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:
293+
294+``` pascal
295+--- NSString.inc (revision 45778)
296++++ NSString.inc (working copy)
297+@@ -105,6 +105,7 @@
298+ function characterAtIndex (index: NSUInteger): unichar; message 'characterAtIndex:';
299+ function init: instancetype; message 'init'; { NS_DESIGNATED_INITIALIZER }
300+ function initWithCoder (aDecoder: NSCoder): instancetype; message 'initWithCoder:'; { NS_DESIGNATED_INITIALIZER }
301++ function initWithData_encoding(data: NSData; encoding: NSStringEncoding) : instancetype; message 'initWithData:encoding:';
302+
303+ { Adopted protocols }
304+ function copyWithZone (zone: NSZonePtr): id; message 'copyWithZone:';
305+```
306+
307+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"
308+
309+I use the following script (for FPC 3.3.1; substitute your FPC version numbers as appropriate) to recompile FPC:
310+
311+``` sh
312+#!/bin/sh
313+cd /usr/local/share/fpcsrc/fpc-3.3.1/
314+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/"
315+make install FPC=$PWD/compiler/ppcx64 OS_TARGET=darwin CPU_TARGET=x86_64
316+```
317+
318+- Note 1: The highlighted line(s) above should be all on one line.
319+- Note 2: You will almost certainly have to use *sudo* to execute that script successfully or face permissions problems.
320+
321+## Retrieving data using a custom delegate
322+
323+When using a custom delegate to retrieve data, the delegate must implement at least the following methods:
324+
325+- URLSession:dataTask:didReceiveData: Tells the delegate that the data task has received some of the expected data.
326+- URLSession:task:didCompleteWithError: Tells the delegate that the data task finished transferring the data.
327+
328+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.
329+
330+### Example code
331+
332+``` pascal
333+unit Unit1;
334+
335+{$mode objfpc}{$H+}
336+{$modeswitch objectivec1}
337+
338+interface
339+
340+uses
341+ Forms, // for the main form
342+ Dialogs, // for ShowMessage
343+ StdCtrls, // for the button
344+ SysUtils, // for IntToStr()
345+ CocoaAll, // for NSData and other Cocoa types
346+ CocoaUtils, Classes; // for NSStringString
347+
348+type
349+ // redefine version from packages/cocoaint/src/foundation/NSURLSession.inc
350+ NSURLSession = objcclass external (NSObject)
351+ public
352+ class function sessionWithConfiguration(configuration: NSURLSessionConfiguration): NSURLSession;
353+ message 'sessionWithConfiguration:';
354+ class function sessionWithConfiguration_delegate_delegateQueue(configuration: NSURLSessionConfiguration; delegate: NSURLSessionDelegateProtocol; queue: NSOperationQueue): NSURLSession;
355+ message 'sessionWithConfiguration:delegate:delegateQueue:';
356+ function dataTaskWithURL(url: NSURL): NSURLSessionDataTask;
357+ message 'dataTaskWithURL:';
358+ end;
359+
360+ { TMyDelegate }
361+ TMyDelegate = objcclass(NSObject, NSURLSessionDelegateProtocol)
362+ private
363+
364+ public
365+ procedure URLSession_dataTask_didReceiveData (session: NSURLSession; dataTask: NSURLSessionDataTask; data: NSData);
366+ message 'URLSession:dataTask:didReceiveData:';
367+ procedure URLSession_task_didCompleteWithError (session: NSURLSession; task: NSURLSessionTask; error: NSError);
368+ message 'URLSession:task:didCompleteWithError:';
369+ end;
370+
371+ { TForm1 }
372+
373+ TForm1 = class(TForm)
374+ Button1: TButton;
375+ procedure Button1Click(Sender: TObject);
376+ private
377+
378+ public
379+
380+ end;
381+
382+var
383+ Form1: TForm1;
384+ myCache: NSURLcache;
385+ responseData: NSMutableData;
386+ queue: NSOperationQueue;
387+ sessionDelegate: TMyDelegate;
388+ webData: NSString;
389+ webError: String;
390+ ThreadDidFinish: PRTLEvent;
391+
392+implementation
393+
394+{$R *.lfm}
395+
396+{ TForm1 }
397+
398+{$DEFINE DEBUG}
399+
400+procedure TMyDelegate.URLSession_dataTask_didReceiveData(session: NSURLSession; dataTask: NSURLSessionDataTask; data: NSData);
401+begin
402+ {$IFDEF DEBUG}
403+ NSLog(NSStr('didReceiveData %i'), data.length);
404+ NSLog(NSStr('didReceiveData %@'), NSString.alloc.initWithData_encoding(data,NSASCIIStringEncoding).autorelease);
405+ {$ENDIF}
406+
407+ // Append the new data to the response variable
408+ responseData.appendData(data);
409+end;
410+
411+procedure TMyDelegate.URLSession_task_didCompleteWithError(session: NSURLSession; task: NSURLSessionTask; error: NSError);
412+begin
413+ {$IFDEF DEBUG}
414+ NSLog(NSStr('didCompleteWithError start'));
415+ NSLog(NSStr('responseData.length %i'), responseData.length);
416+ NSLog(NSStr('responseData %@'), NSString.alloc.initWithData_encoding(responseData,NSASCIIStringEncoding).autorelease);
417+ {$ENDIF}
418+
419+ // Is there an error?
420+ if(responseData.length = 0) then
421+ begin
422+ NSLog(NSStr('Error %@'), error.description);
423+ webError := 'Error retrieving: ' + NSStringToString(error.userInfo.valueForKey(NSErrorFailingUrlStringKey))
424+ + LineEnding + LineEnding + 'Reason: ' + NSStringToString(error.localizedDescription);
425+ end
426+ else
427+ begin
428+ webError := '';
429+ webData := NSString.alloc.initWithData_encoding(responseData,NSASCIIStringEncoding);
430+ end;
431+
432+ // notify main thread that data retrieval thread has finished
433+ RTLEventSetEvent(ThreadDidFinish);
434+
435+ {$IFDEF DEBUG}
436+ NSLog(NSStr('didCompleteWithError finish'));
437+ {$ENDIF}
438+end;
439+
440+procedure TForm1.Button1Click(Sender: TObject);
441+var
442+ urlSessionConfig: NSURLSessionConfiguration = Nil;
443+ cachePath: NSString = Nil;
444+ urlSession: NSURLSession = Nil;
445+ URL: NSURL = Nil;
446+begin
447+ // create event to synchronise data retrieval background thread
448+ // with the GUI main thread
449+ ThreadDidFinish := RTLEventCreate;
450+
451+ // create default url session config
452+ urlSessionConfig := NSURLSessionConfiguration.defaultSessionConfiguration;
453+
454+ // create connection delegate
455+ sessionDelegate := TMyDelegate.alloc.init;
456+
457+ // create responseData
458+ responseData := NSMutableData.alloc.init;
459+
460+ // configure caching behavior for the default session
461+ cachePath := NSTemporaryDirectory.stringByAppendingPathComponent(NSStr('/nsurlsessiondemo.cache'));
462+
463+ {$IFDEF DEBUG}
464+ NSLog(NSStr('Cache path: %@'), cachePath);
465+ {$ENDIF}
466+
467+ myCache := NSURLCache.alloc.initWithMemoryCapacity_diskCapacity_diskPath(16384, 268435456, cachePath);
468+ urlSessionConfig.setURLCache(myCache);
469+
470+ // set cache policy
471+ {$IFDEF DEBUG}
472+ urlSessionConfig.setRequestCachePolicy(NSURLRequestReloadIgnoringLocalCacheData);
473+ {$ELSE}
474+ urlSessionConfig.setRequestCachePolicy(NSURLRequestUseProtocolCachePolicy);
475+ {$ENDIF}
476+
477+ // create a session for configuration
478+ urlSession := NSURLSession.sessionWithConfiguration_delegate_delegateQueue(urlSessionConfig, sessionDelegate, queue);
479+
480+ // create NSURL
481+ URL := NSURL.URLWithString(NSSTR(PAnsiChar('https://sentinel.sentry.org/')));
482+ if(Url = Nil) then
483+ ShowMessage('NSURL.URLWithString failed!');
484+
485+ // setup and execute data task
486+ urlSession.dataTaskWithURL(URL).resume;
487+
488+ // wait for data retrieval thread to finish
489+ RTLEventWaitFor(ThreadDidFinish);
490+
491+ // Show result
492+ if(webError <> '') then
493+ ShowMessage(webError)
494+ else
495+ ShowMessage(NSStringToString(webData));
496+
497+ // housekeeping
498+ RTLeventdestroy(ThreadDidFinish);
499+ sessionDelegate.release;
500+ responseData.release;
501+ myCache.release;
502+ webData.release;
503+end;
504+
505+end.
506+```
507+
508+Full project source code is available from [SourceForge](https://sourceforge.net/p/lazarus-wiki-projects/code/ci/master/tree/laz_nsurlsession2/).
509+
510+##### Compilation note
511+
512+See the previous Compilation note above.
513+
514+## Downloading files
515+
516+At a high level, downloading a file is similar to retrieving data. Your application should implement the following delegate methods:
517+
518+- **URLSession:downloadTask:didFinishDownloadingToURL**: provides your application with the URL to a temporary file where the downloaded content is stored.
519+
520+- **URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite**: provides your application with status information about the progress of the download.
521+
522+- **URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes**: tells your application that its attempt to resume a previously failed download was successful.
523+
524+- **URLSession:task:didCompleteWithError**: tells your application that the download failed.
525+
526+If you schedule the download in a background session, the download continues when your application is not running. If you schedule the download in a default or ephemeral session, the download must begin anew when your application is relaunched.
527+
528+While the example below only implements a few of the delegate methods, it should be simple enough for anyone to understand how to add the missing ones. The example application downloads a file to the user's Downloads folder. If the downloaded file already exists in the Downloads folder, it is removed and the just downloaded file will take its place.
529+
530+### Example code
531+
532+``` pascal
533+unit Unit1;
534+
535+{$mode objfpc}{$H+}
536+{$modeswitch objectivec1}
537+
538+interface
539+
540+uses
541+ Forms, // for the main form
542+ Dialogs, // for ShowMessage
543+ StdCtrls, // for the button
544+ SysUtils, // for IntToStr()
545+ CocoaAll, // for NSData and other Cocoa types
546+ CTypes; // for cInt64
547+
548+type
549+ { TMyDlDelegate }
550+ TMyDlDelegate = objcclass(NSObject, NSURLSessionDelegateProtocol)
551+ private
552+
553+ public
554+ procedure URLSession_downloadtask_didFinishDownloadingToURL(session: NSURLSession; downloadTask: NSURLSessionDownloadTask;
555+ location: NSURL);
556+ message 'URLSession:downloadTask:didFinishDownloadingToURL:';
557+ procedure URLSession_downloadTask_didWriteData_totalBytesWritten_totalBytesExpectedToWrite (session: NSURLSession;
558+ downloadTask: NSURLSessionDownloadTask; bytesWritten: cint64; totalBytesWritten: cint64; totalBytesExpectedToWrite: cint64);
559+ message 'URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:';
560+ {procedure URLSession_downloadTask_didResumeAtOffset_expectedTotalBytes (session: NSURLSession;
561+ downloadTask: NSURLSessionDownloadTask; fileOffset: cint64; expectedTotalBytes: cint64);
562+ message 'URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:';}
563+ end;
564+
565+ { TForm1 }
566+
567+ TForm1 = class(TForm)
568+ Button1: TButton;
569+ procedure Button1Click(Sender: TObject);
570+ private
571+
572+ public
573+
574+ end;
575+
576+var
577+ Form1: TForm1;
578+
579+implementation
580+
581+{$R *.lfm}
582+
583+{ TForm1 }
584+
585+{$DEFINE DEBUG}
586+
587+//
588+// Delegate methods
589+//
590+procedure TMyDlDelegate.URLSession_downloadtask_didFinishDownloadingToURL(session: NSURLSession;
591+ downloadTask: NSURLSessionDownloadTask; location: NSURL);
592+var
593+ downloadsPath: NSString;
594+ downloadsDirectoryURL: NSURL;
595+ downloadURL: NSURL;
596+ error: NSError;
597+ filePath: NSString;
598+begin
599+ downloadsPath := NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, True).firstObject;
600+ downloadsDirectoryURL := NSURL.fileURLWithPath(downloadsPath);
601+ downloadURL := downloadsDirectoryURL.URLByAppendingPathComponent(downloadTask.response.suggestedFilename);
602+ filePath := downloadsPath.stringByAppendingPathComponent(downloadTask.response.suggestedFilename);
603+
604+ {$IFDEF DEBUG}
605+ NSLog(NSStr('Session %@ Download task %@ Finished downloading to URL %@'), session, downloadTask, location);
606+ NSLog(NSStr('-------------------------------------------'));
607+ NSLog(NSStr('downloads path: %@'), downloadsPath);
608+ NSLog(NSStr('downloads directory URL: %@'), downloadsDirectoryURL);
609+ NSLog(NSStr('download URL: %@'), downloadURL);
610+ NSLog(NSStr('file path: %@'), filePath);
611+ NSLog(NSStr('-------------------------------------------'));
612+ {$ENDIF}
613+
614+ // remove any old file from the destination directory
615+ if(NSFileManager.defaultManager.fileExistsAtPath(filePath)) then
616+ begin
617+ NSLog(NSStr('Oh no, file already exists in downloads directory! Will remove for you :-)'));
618+ if (NSFileManager.defaultManager.removeItemAtPath_error(filePath, @error) <> True) then
619+ NSLog(NSStr('Oh no, removal of %@ failed, giving up :-('), filePath);
620+ end;
621+
622+ // file move error
623+ if(NSFileManager.defaultManager.moveItemAtURL_toURL_error(location,downloadURL, @Error) <> True) then
624+ NSLog(NSStr('Download error %@'), Error.localizedDescription);
625+end;
626+
627+procedure TMyDlDelegate.URLSession_downloadTask_didWriteData_totalBytesWritten_totalBytesExpectedToWrite(session: NSURLSession;
628+ downloadTask: NSURLSessionDownloadTask; bytesWritten: cint64; totalBytesWritten: cint64; totalBytesExpectedToWrite: cint64);
629+begin
630+ NSLog(NSStr('Session %@ download task %@ wrote an additional %lld bytes (total %lld bytes) out of an expected %lld bytes.'),
631+ session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
632+end;
633+
634+//
635+// Download button handler
636+//
637+procedure TForm1.Button1Click(Sender: TObject);
638+var
639+ dlReq: NSURL = Nil;
640+ dlSessionConfig: NSURLSessionConfiguration = Nil;
641+ dlSession: NSURLSession = Nil;
642+ dlTask: NSURLSessionDownloadTask = Nil;
643+ dlcache: NSURLcache;
644+ dlcachePath: NSString = Nil;
645+ dlQueue: NSOperationQueue = Nil;
646+ dlDelegate: TMyDlDelegate = Nil;
647+begin
648+ // create request
649+ dlReq := NSURL.URLWithString(NSStr('https://www.sentry.org/microlab/ASM_19930531.ZIP'));
650+ if(dlReq = Nil) then
651+ begin
652+ ShowMessage('NSURL.URLWithString failed! Aborting...');
653+ Exit;
654+ end;
655+
656+ // create download delegate
657+ dlDelegate := TMyDlDelegate.alloc.init;
658+
659+ // create background session config
660+ dlSessionConfig := NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(NSStr('dtask01'));
661+
662+ // create a session with background session configuration
663+ dlSession := NSURLSession.sessionWithConfiguration_delegate_delegateQueue(dlSessionConfig, dlDelegate, dlQueue);
664+
665+ // configure caching behavior for the session configuration
666+ dlCachePath := NSTemporaryDirectory.stringByAppendingPathComponent(NSStr('/nsurlsessiondemo.cache'));
667+ dlCache := NSURLCache.alloc.initWithMemoryCapacity_diskCapacity_diskPath(16384, 268435456, dlCachePath);
668+ dlSessionConfig.setURLCache(dlCache);
669+
670+ // log cache path
671+ {$IFDEF DEBUG}
672+ NSLog(NSStr('Cache path: %@'), dlCachePath);
673+ {$ENDIF}
674+
675+ // set cache policy
676+ {$IFDEF DEBUG}
677+ dlSessionConfig.setRequestCachePolicy(NSURLRequestReloadIgnoringLocalCacheData);
678+ {$ELSE}
679+ dlSessionConfig.setRequestCachePolicy(NSURLRequestUseProtocolCachePolicy);
680+ {$ENDIF}
681+
682+ // setup download task
683+ dlTask := dlSession.downloadTaskWithURL(dlReq);
684+
685+ // execute download task
686+ dlTask.resume;
687+
688+ // housekeeping
689+ dlDelegate.release;
690+ dlCache.release;
691+ dlSession.finishTasksAndInvalidate;
692+end;
693+
694+end.
695+```
696+
697+Full project source code is available from [SourceForge](https://sourceforge.net/p/lazarus-wiki-projects/code/ci/master/tree/laz_nsurlsession3/).
698+
699+## Downloading files with graphical user interface feedback
700+
701+You may have noticed that all the user feedback in the previous example has been relegated to NSLog entries. There is a reason for this. Any attempt to provide user feedback to the graphical user interface from within a delegate method running on a secondary or background thread will cause the application to die with a log entry similar to this:
702+
703+` *** Terminating app due to uncaught exception 'NSInternalInconsistencyException',`\
704+` reason: 'NSWindow drag regions should only be invalidated on the Main Thread!'`
705+
706+The cause? Apple’s UI frameworks, and Cocoa in particular, can only be called from the main thread. This means that if you have a background threading process, it cannot interact with the user interface because all user interface objects are marked as not safe for threading. Touching the user interface from a background thread can cause all sorts of issues, including corruption of internal state, crashes, or inexplicable incorrect behaviour.
707+
708+The solution? *performSelectorOnMainThread:withObject:waitUntilDone:*. The selector you specify will be dispatched when the run loop of the main thread is in the default mode. When the run loop is in another mode, the selector will only be executed when the run loop is switched to the default mode. You can use *performSelectorOnMainThread:withObject:waitUntilDone:modes:* to specify the mode(s) if necessary.
709+
710+The example below implements *performSelectorOnMainThread:withObject:waitUntilDone:* in two places and uses an application-wide object (TdlStatsuObj) to update the content of a memo on the form with status information about the progress of the download.
711+
712+### Example code
713+
714+``` pascal
715+unit Unit1;
716+
717+{$mode objfpc}{$H+}
718+{$modeswitch objectivec1}
719+
720+interface
721+
722+uses
723+ Forms, // for the main form
724+ Dialogs, // for ShowMessage
725+ StdCtrls, // for the button
726+ SysUtils, // for IntToStr()
727+ CocoaAll, // for NSData and other Cocoa types
728+ CocoaUtils, // for NSTringToString
729+ CTypes; // for cInt64
730+
731+type
732+ { TDownloadlDelegate }
733+ TDownloadlDelegate = objcclass(NSObject, NSURLSessionDelegateProtocol)
734+ private
735+
736+ public
737+ procedure URLSession_downloadtask_didFinishDownloadingToURL(session: NSURLSession; downloadTask: NSURLSessionDownloadTask;
738+ location: NSURL);
739+ message 'URLSession:downloadTask:didFinishDownloadingToURL:';
740+ procedure URLSession_downloadTask_didWriteData_totalBytesWritten_totalBytesExpectedToWrite (session: NSURLSession;
741+ downloadTask: NSURLSessionDownloadTask; bytesWritten: cint64; totalBytesWritten: cint64; totalBytesExpectedToWrite: cint64);
742+ message 'URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:';
743+ procedure updateProgress;
744+ message 'updateProgess';
745+ procedure downloadFinished;
746+ message 'downloadFinished';
747+ end;
748+
749+ { TdlStatsuObj - application-wide object to pass to main thread for GUI status updates}
750+ TdlStatusObj = objcclass(NSObject)
751+ private
752+ _BytesRx: Int64;
753+ _TotalBytesRx: Int64;
754+ _ExpectedTotalBytes: Int64;
755+ _Location: NSString;
756+ public
757+ procedure setBytesRx(newValue: Int64);
758+ message 'setBytesRx:';
759+ function getBytesRx: Int64;
760+ message 'getBytesRx';
761+ procedure setTotalBytesRx(newValue: Int64);
762+ message 'setTotalBytesRx:';
763+ function getTotalBytesRx: Int64;
764+ message 'getTotalBytesRx';
765+ procedure setExpectedTotalBytes(newValue: Int64);
766+ message 'setExpectedTotalBytes:';
767+ function getExpectedTotalBytes: Int64;
768+ message 'getExpectedTotalBytes';
769+ procedure setLocation(newValue: NSString);
770+ message 'setLocation:';
771+ function getLocation: NSString;
772+ message 'getLocation';
773+ end;
774+
775+ { TForm1 }
776+
777+ TForm1 = class(TForm)
778+ Button1: TButton;
779+ Memo1: TMemo;
780+ procedure Button1Click(Sender: TObject);
781+ private
782+
783+ public
784+
785+ end;
786+
787+var
788+ Form1: TForm1;
789+ dlStatusObj: TdlStatusObj;
790+
791+implementation
792+
793+{$R *.lfm}
794+
795+{ TForm1 }
796+
797+//{$DEFINE DEBUG}
798+
799+//
800+// TdlStatusObj methods
801+//
802+procedure TdlStatusObj.setBytesRx(newValue: Int64);
803+begin
804+ _BytesRx := newValue;
805+end;
806+
807+function TdlStatusObj.getBytesRx: Int64;
808+begin
809+ getBytesRx := _BytesRx;
810+end;
811+
812+procedure TdlStatusObj.setTotalBytesRx(newValue: Int64);
813+begin
814+ _TotalBytesRx := newValue;
815+end;
816+
817+function TdlStatusObj.getTotalBytesRx: Int64;
818+begin
819+ getTotalBytesRx := _TotalBytesRx;
820+end;
821+
822+procedure TdlStatusObj.setExpectedTotalBytes(newValue: Int64);
823+begin
824+ _ExpectedTotalBytes := newValue;
825+end;
826+
827+function TdlStatusObj.getExpectedTotalBytes: Int64;
828+begin
829+ getExpectedTotalBytes := _ExpectedTotalBytes;
830+end;
831+
832+procedure TdlStatusObj.setLocation(newValue: NSString);
833+begin
834+ _Location := newValue;
835+end;
836+
837+function TdlStatusObj.getLocation: NSString;
838+begin
839+ getLocation := _Location;
840+end;
841+
842+//
843+// Delegate methods
844+//
845+procedure TDownloadlDelegate.URLSession_downloadtask_didFinishDownloadingToURL(session: NSURLSession;
846+ downloadTask: NSURLSessionDownloadTask; location: NSURL);
847+var
848+ downloadsPath: NSString;
849+ downloadsDirectoryURL: NSURL;
850+ downloadURL: NSURL;
851+ error: NSError;
852+ filePath: NSString;
853+ aSel: SEL;
854+begin
855+ downloadsPath := NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, True).firstObject;
856+ downloadsDirectoryURL := NSURL.fileURLWithPath(downloadsPath);
857+ downloadURL := downloadsDirectoryURL.URLByAppendingPathComponent(downloadTask.response.suggestedFilename);
858+ filePath := downloadsPath.stringByAppendingPathComponent(downloadTask.response.suggestedFilename);
859+
860+ {$IFDEF DEBUG}
861+ NSLog(NSStr('-------------------------------------------'));
862+ NSLog(NSStr('downloads path: %@'), downloadsPath);
863+ NSLog(NSStr('downloads directory URL: %@'), downloadsDirectoryURL);
864+ NSLog(NSStr('download URL: %@'), downloadURL);
865+ NSLog(NSStr('file path: %@'), filePath);
866+ NSLog(NSStr('-------------------------------------------'));
867+ NSLog(NSStr('Session %@ Download task %@ Finished downloading to URL %@'), session, downloadTask, location);
868+ {$ENDIF}
869+
870+ // populate download status object
871+ dlStatusObj.setLocation(filePath);
872+
873+ // update the user interface on the main thread.
874+ aSel := ObjCSelector(TDownloadlDelegate.downloadFinished);
875+ self.performSelectorOnMainThread_withObject_waitUntilDone(aSel, dlStatusObj, true);
876+
877+ // remove any old file from the destination directory
878+ if(NSFileManager.defaultManager.fileExistsAtPath(filePath)) then
879+ begin
880+ {$IFDEF DEBUG}
881+ NSLog(NSStr('Oh no, file already exists in downloads directory! Will remove for you :-)'));
882+ {$ENDIF}
883+ if (NSFileManager.defaultManager.removeItemAtPath_error(filePath, @error) <> True) then
884+ begin
885+ {$IFDEF DEBUG}
886+ NSLog(NSStr('Oh no, removal of %@ failed with erro %@'), filePath, error.localizedDescription);
887+ {$ENDIF}
888+ end;
889+ end;
890+
891+ // file move error
892+ if(NSFileManager.defaultManager.moveItemAtURL_toURL_error(location,downloadURL, @Error) <> True) then
893+ begin
894+ {$IFDEF DEBUG}
895+ NSLog(NSStr('Download error %@'), Error.localizedDescription);
896+ {$ENDIF}
897+ end;
898+end;
899+
900+procedure TDownloadlDelegate.URLSession_downloadTask_didWriteData_totalBytesWritten_totalBytesExpectedToWrite(session: NSURLSession;
901+ downloadTask: NSURLSessionDownloadTask; bytesWritten: cint64; totalBytesWritten: cint64; totalBytesExpectedToWrite: cint64);
902+var
903+ aSel: SEL;
904+begin
905+ {$IFDEF DEBUG}
906+ NSLog(NSStr('Session %@ download task %@ wrote an additional %lld bytes (total %lld bytes) out of an expected %lld bytes.'),
907+ session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
908+ {$ENDIF}
909+
910+ // populate status object
911+ dlStatusObj.setBytesRx(bytesWritten);
912+ dlStatusObj.setTotalBytesRx(totalBytesWritten);
913+ dlStatusObj.setExpectedTotalBytes(totalBytesExpectedToWrite);
914+
915+ // update the user interface on the main thread.
916+ aSel := ObjCSelector(TDownloadlDelegate.updateProgress);
917+ self.performSelectorOnMainThread_withObject_waitUntilDone(aSel, dlStatusObj, true);
918+end;
919+
920+procedure TDownloadlDelegate.updateProgress;
921+begin
922+ Form1.Memo1.Append('Bytes received: ' + IntToStr(dlStatusObj.getBytesRx));
923+ Form1.Memo1.Append('Total bytes received: ' + IntToStr(dlStatusObj.getTotalBytesRx));
924+ Form1.Memo1.Append('Expected total bytes: ' + IntToStr(dlStatusObj.getExpectedTotalBytes));
925+ Form1.Memo1.Append('---');
926+end;
927+
928+procedure TDownloadlDelegate.downloadFinished;
929+begin
930+ Form1.Memo1.Append('Download of ' + NSStringToString(dlStatusObj.getLocation) + ' finished!');
931+end;
932+
933+//
934+// Download button handler
935+//
936+procedure TForm1.Button1Click(Sender: TObject);
937+var
938+ dlReq: NSURL = Nil;
939+ dlSessionConfig: NSURLSessionConfiguration = Nil;
940+ dlSession: NSURLSession = Nil;
941+ dlTask: NSURLSessionDownloadTask = Nil;
942+ dlcache: NSURLcache;
943+ dlcachePath: NSString = Nil;
944+ dlQueue: NSOperationQueue = Nil;
945+ dlDelegate: TDownloadlDelegate = Nil;
946+begin
947+ // create request
948+ dlReq := NSURL.URLWithString(NSStr('https://www.sentry.org/microlab/Microlab_Teach-In-93-Pt12.pdf'));
949+ if(dlReq = Nil) then
950+ begin
951+ ShowMessage('NSURL.URLWithString failed! Aborting...');
952+ Exit;
953+ end;
954+
955+ // create download delegate
956+ dlDelegate := TDownloadlDelegate.alloc.init;
957+
958+ // create background session config
959+ dlSessionConfig := NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(NSStr('dtask01'));
960+
961+ // create a session with background session configuration
962+ dlSession := NSURLSession.sessionWithConfiguration_delegate_delegateQueue(dlSessionConfig, dlDelegate, dlQueue);
963+
964+ // configure caching behaviour for the session configuration
965+ dlCachePath := NSTemporaryDirectory.stringByAppendingPathComponent(NSStr('/nsurlsessiondemo.cache'));
966+ dlCache := NSURLCache.alloc.initWithMemoryCapacity_diskCapacity_diskPath(16384, 268435456, dlCachePath);
967+ dlSessionConfig.setURLCache(dlCache);
968+
969+ // log cache path
970+ {$IFDEF DEBUG}
971+ NSLog(NSStr('Cache path: %@'), dlCachePath);
972+ {$ENDIF}
973+
974+ // set cache policy
975+ {$IFDEF DEBUG}
976+ dlSessionConfig.setRequestCachePolicy(NSURLRequestReloadIgnoringLocalCacheData);
977+ {$ELSE}
978+ dlSessionConfig.setRequestCachePolicy(NSURLRequestUseProtocolCachePolicy);
979+ {$ENDIF}
980+
981+ // setup download task
982+ dlTask := dlSession.downloadTaskWithURL(dlReq);
983+
984+ // create download status object
985+ dlStatusObj := TdlStatusObj.alloc.init;
986+
987+ // execute download task
988+ dlTask.resume;
989+
990+ // housekeeping
991+ dlDelegate.release;
992+ dlCache.release;
993+ dlSession.finishTasksAndInvalidate;
994+end;
995+
996+end.
997+```
998+
999+Note that this is a very minimal demonstration application. In a real application you would want to, for example, extend the application-wide object (TdlStatus) to include any error messages which are still being handled by NSlog in the above example.
1000+
1001+Full project source code is available from [SourceForge](https://sourceforge.net/p/lazarus-wiki-projects/code/ci/master/tree/laz_nsurlsession4/).
1002+
1003+## See also
1004+
1005+- [[macOS NSURLConnection]] deprecated in favour of [[macOS NSURLSession]].
1006+- [[fpwebview]] - Free Pascal binding for webview, a cross-platform library that links Cocoa/WebKit on macOS.
1007+
1008+## External links
1009+
1010+- [Apple: NSString](https://developer.apple.com/documentation/foundation/nsstring).
1011+- [Apple: NSURL](https://developer.apple.com/documentation/foundation/nsurl?language=objc).
1012+- [Apple: NSURLCache](https://developer.apple.com/documentation/foundation/nsurlcache).
1013+- [Apple: NSURLSession](https://developer.apple.com/documentation/foundation/nsurlsession).
1014+- [Apple: NSURLRequest](https://developer.apple.com/documentation/foundation/nsurlrequest).
1015+- [Apple: NSURLSessionDownloadTask](https://developer.apple.com/documentation/foundation/nsurlsessiondownloadtask).
1016+- [Apple: NSURLSessionConfiguration](https://developer.apple.com/documentation/foundation/nsurlsessionconfiguration).
1017+- [Apple: NSURLResponse](https://developer.apple.com/documentation/foundation/nsurlresponse).
1018+- [Apple: NSHTTPURLResponse](https://developer.apple.com/documentation/foundation/nshttpurlresponse).
1019+- [Apple: performSelectorOnMainThread:withObject:waitUntilDone](https://developer.apple.com/documentation/objectivec/nsobject/1414900-performselectoronmainthread).
1020+- [Apple: Thread Programming Guide - Threads and Your User Interface](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/AboutThreads/AboutThreads.html#//apple_ref/doc/uid/10000057i-CH6-SW21).
1021+- [Apple: Network Framework](https://developer.apple.com/documentation/network) on which NSURLSession is built.
1022+- [Apple: NSAppTransportSecurity](https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity).
1023+
1024+---
1025+*From the Free Pascal wiki, page "macOS NSURLSession", as it stood on 2022-02-21 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history