public void CreateSession(string sessionID)
        {
            lock (syncRoot)
                if (session == null)
                {
                    using (var configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(sessionID))
                    {
                        configuration.HttpShouldSetCookies           = true;
                        configuration.HttpCookieAcceptPolicy         = NSHttpCookieAcceptPolicy.Always;
                        configuration.HttpCookieStorage.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
                        configuration.AllowsCellularAccess           = false;
                        configuration.HttpMaximumConnectionsPerHost  = 1;
                        configuration.SessionSendsLaunchEvents       = true;
                        configuration.TimeoutIntervalForRequest      = 0;
                        session = NSUrlSession.FromConfiguration(
                            configuration,
                            new DownloadSessionDelegate(this),
                            new NSOperationQueue()
                        {
                            MaxConcurrentOperationCount = 1
                        });
                    }

                    Logger.Log("INFO: ItemDownloader session created");
                }
        }
Exemple #2
0
        public HttpTransferManager(AppleLifecycle lifecycle,
                                   ILogger <IHttpTransferManager> logger,
                                   IPlatform platform,
                                   int maxConnectionsPerHost = 1)
        {
            this.platform = platform;
            this.logger   = logger;

            this.sessionDelegate = new ShinyUrlSessionDelegate(this, logger, platform);
            this.sessionConfig   = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(SessionName);
            this.sessionConfig.HttpMaximumConnectionsPerHost = maxConnectionsPerHost;
            this.sessionConfig.RequestCachePolicy            = NSUrlRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData;

            var s = this.Session; // force load

            lifecycle.RegisterHandleEventsForBackgroundUrl((sessionIdentifier, completionHandler) =>
            {
                if (!SessionName.Equals(sessionIdentifier))
                {
                    return(false);
                }

                ShinyUrlSessionDelegate.CompletionHandler = completionHandler;
                return(true);
            });
        }
        async void Tick()
        {
            var downloadmanager = new MyDownloadManager();

            var downloadqueue = new NSOperationQueue {
                MaxConcurrentOperationCount = 1
            };

            string       sessionidentifier = "myapp.download.images";
            NSUrlSession nsurlsession      = null;

            using (var configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(sessionidentifier)) {
                nsurlsession = NSUrlSession.FromConfiguration(configuration, downloadmanager, downloadqueue);
            }

            for (int i = 0; i < 2000; i++)
            {
                var image = string.Format("https://xamarin.com/content/images/pages/index/[email protected]?id={0}", i);

                var ii = i;
                NSTimer.CreateScheduledTimer(TimeSpan.FromMilliseconds(10 + i / 10), (v) => {
                    using (var url = NSUrl.FromString(image)) {
                        using (var request = NSUrlRequest.FromUrl(url)) {
                            var task = nsurlsession.CreateDownloadTask(request);
                            task.Resume();
                            Console.WriteLine("Created task #{0}: {1}", ii, task);
                        }
                    }
                });
            }
        }
 public NSUrlSession InitBackgroundSession()
 {
     Console.WriteLine("InitBackgroundSession");
     using (var configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(Identifier)) {
         return(NSUrlSession.FromConfiguration(configuration, new UrlSessionDelegate(this), null));
     }
 }
Exemple #5
0
        /// <summary>
        /// Initializes the session.
        /// </summary>
        void InitializeSession()
        {
            // Initialize our session config. We use a background session to enabled out of process uploads/downloads. Note that there are other configurations available:
            // - DefaultSessionConfiguration: behaves like NSUrlConnection. Used if *background* transfer is not required.
            // - EphemeralSessionConfiguration: use if you want to achieve something like private browsing where all sesion info (e.g. cookies) is kept in memory only.
            using (var sessionConfig = UIDevice.CurrentDevice.CheckSystemVersion(8, 0)
                                ? NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(sessionId)
                                : NSUrlSessionConfiguration.BackgroundSessionConfiguration(sessionId))
            {
                // Allow downloads over cellular network too.
                sessionConfig.AllowsCellularAccess = true;

                // Give the OS a hint about what we are downloading. This helps iOS to prioritize. For example "Background" is used to download data that was not requested by the user and
                // should be ready if the app gets activated.
                sessionConfig.NetworkServiceType = NSUrlRequestNetworkServiceType.Default;

                // Configure how many downloads we allow at the same time. Set to 2 to see that further downloads start once the first two have been completed.
                sessionConfig.HttpMaximumConnectionsPerHost = 2;

                // Create a session delegate and the session itself
                // Initialize the session itself with the configuration and a session delegate.
                var sessionDelegate = new CustomSessionDownloadDelegate(this);
                this.session = NSUrlSession.FromConfiguration(sessionConfig, (INSUrlSessionDelegate)sessionDelegate, null);
            }
        }
        public DownloadManager(IRepository repository)
        {
            this.repository      = repository;
            this.sessionDelegate = new CoreSessionDownloadDelegate();
            this.sessionConfig   = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(NSBundle.MainBundle.BundleIdentifier + ".BackgroundTransferSession");
            this.session         = NSUrlSession.FromConfiguration(
                this.sessionConfig,
                this.sessionDelegate,
                new NSOperationQueue()
                );

            //this.session.GetTasks2((_, uploads, downloads) =>
            //{
            //    foreach (NSUrlSessionUploadTask upload in uploads)
            //    {
            //        // TODO: need localFilePath for what WAS uploading
            //        // TODO: need to set resumed status
            //        //this.Add(new HttpTask(this.ToTaskConfiguration(upload), upload));
            //        upload.Resume();
            //    }

            //    foreach (var download in downloads)
            //    {
            //        //this.Add(new HttpTask(this.ToTaskConfiguration(download), download));
            //        download.Resume();
            //    }
            //});
        }
        public HttpTransferTasks()
        {
            this.sessionDelegate = new PluginSessionDelegate();
            this.sessionConfig   = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(NSBundle.MainBundle.BundleIdentifier + ".BackgroundTransferSession");
            this.sessionConfig.HttpMaximumConnectionsPerHost = 1;
            this.session = NSUrlSession.FromConfiguration(
                this.sessionConfig,
                this.sessionDelegate,
                new NSOperationQueue()
                );

            this.session.GetTasks2((_, uploads, downloads) =>
            {
                foreach (NSUrlSessionUploadTask upload in uploads)
                {
                    // TODO: need localFilePath for what WAS uploading
                    // TODO: need to set resumed status
                    this.Add(new HttpTask(this.ToTaskConfiguration(upload), upload));
                    upload.Resume();
                }

                foreach (var download in downloads)
                {
                    this.Add(new HttpTask(this.ToTaskConfiguration(download), download));
                    download.Resume();
                }
            });
        }
Exemple #8
0
        public HttpTransferManager(int maxConnectionsPerHost = 1)
        {
            this.sessionDelegate = new ShinyUrlSessionDelegate(this);
            this.sessionConfig   = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(SessionName);
            this.sessionConfig.HttpMaximumConnectionsPerHost = maxConnectionsPerHost;
            this.sessionConfig.RequestCachePolicy            = NSUrlRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData;

            var s = this.Session; // force load
        }
Exemple #9
0
        public NSUrlSession GetSession(string identifier)
        {
            var configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(identifier);

            // max timeout is one hour...

            configuration.TimeoutIntervalForResource = 60 * 60;

            return(NSUrlSession.FromConfiguration(configuration, (INSUrlSessionDelegate)Delegate, NSOperationQueue.MainQueue));
        }
Exemple #10
0
        void ScheduleURLSession()
        {
            var uuuid = new NSUuid();
            var backgroundConfigObject = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(uuuid.AsString());

            backgroundConfigObject.SessionSendsLaunchEvents = true;
            var backgroundSession = NSUrlSession.FromConfiguration(backgroundConfigObject);
            var downloadTask      = backgroundSession.CreateDownloadTask(sampleDownloadURL);

            downloadTask.Resume();
        }
Exemple #11
0
        public override void HandleEventsForBackgroundUrl(
            UIApplication application,
            string sessionIdentifier,
            [BlockProxy(typeof(AdAction))]
            Action completionHandler)
        {
            var configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(sessionIdentifier);

            XamarinFileUploader.FileUploaderService.Instance.Delegate.CompletionHandler = completionHandler;

            var session = NSUrlSession.FromWeakConfiguration(configuration, XamarinFileUploader.FileUploaderService.Instance.Delegate, NSOperationQueue.MainQueue);
        }
        private NSUrlSession initBackgroundSession(Action <int> onPercentUpdate, object CancellationToken)
        {
            // Because eventually NSUrlSession.FromConfiguration must receive an interface as a param (INSUrlSessionDelegate),
            // we have to assign whatever properties we are listening for here.
            _urlSessionDelegate = new UrlSessionDelegate(this, onPercentUpdate, CancellationToken);

            System.Diagnostics.Debug.WriteLine("InitBackgroundSession");
            using (var configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(identifier))
            {
                return(NSUrlSession.FromConfiguration(configuration, (INSUrlSessionDelegate)_urlSessionDelegate, null));
            }
        }
        NSUrlSession InitBackgroundSession(string identifier)
        {
            Console.WriteLine("InitBackgroundSession");
            configuration = Device.IsIos8
                                        ? NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(identifier)
                                : NSUrlSessionConfiguration.BackgroundSessionConfiguration(identifier);
            configuration.AllowsCellularAccess = true;
            var ses = NSUrlSession.FromConfiguration(configuration, new UrlSessionDelegate(), null);

            ses.GetTasks2((data, upload, downloads) => { restoreTasks(ses, data, upload, downloads); });
            return(ses);
        }
 /// <summary>
 /// Initializes the session.
 /// </summary>
 void InitializeSession()
 {
     // TODO: Initialize NSUrlSession.
     using (var sessionConfig = UIDevice.CurrentDevice.CheckSystemVersion(8, 0)
         ? NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(sessionId)
         : NSUrlSessionConfiguration.BackgroundSessionConfiguration(sessionId))
     {
         sessionConfig.AllowsCellularAccess = true;
         sessionConfig.NetworkServiceType   = NSUrlRequestNetworkServiceType.Default;
         var sessionDelegate = new CustomSessionDownloadDelegate(this);
         this.session = NSUrlSession.FromConfiguration(sessionConfig, sessionDelegate, null);
     }
 }
Exemple #15
0
        public HttpTransferManager(int maxConnectionsPerHost = 1)
        {
            this.sessionDelegate = new ShinyUrlSessionDelegate(this);
            this.sessionConfig   = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(SessionName);
            this.sessionConfig.HttpMaximumConnectionsPerHost = maxConnectionsPerHost;
            this.sessionConfig.RequestCachePolicy            = NSUrlRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData;

            var s = this.Session; // force load
            //this.sessionConfig.Discretionary = true;
            //this.sessionConfig.HttpShouldUsePipelining = true;
            //this.sessionConfig.RequestCachePolicy = NSUrlRequestCachePolicy.ReloadIgnoringCacheData;
            //this.sessionConfig.ShouldUseExtendedBackgroundIdleMode = true;
        }
Exemple #16
0
        public void CreateSessionTest()
        {
            if (!TestRuntime.CheckXcodeVersion(7, 0))
            {
                Assert.Ignore("Ignoring AVAssetDownloadUrlSession tests: Requires iOS9+");
            }

            TestRuntime.AssertNotDevice("Ignoring CreateSessionTest tests: Requires com.apple.developer.media-asset-download entitlement");

            using (var backgroundConfiguration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration("HLS-Identifier")) {
                Assert.DoesNotThrow(() => AVAssetDownloadUrlSession.CreateSession(backgroundConfiguration, null, NSOperationQueue.MainQueue), "Should not throw InvalidCastException");
            }
        }
Exemple #17
0
        public NSUrlSession InitSyncSession()
        {
            ////See URL below for configuration options
            ////https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionConfiguration_class/index.html

            using (var config = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(BackgroundSessionId))
            {
                config.HttpMaximumConnectionsPerHost = 4;     //iOS Default is 4
                config.TimeoutIntervalForRequest     = 600.0; //30min allowance; iOS default is 60 seconds.
                config.TimeoutIntervalForResource    = 120.0; //2min; iOS Default is 7 days

                return(NSUrlSession.FromConfiguration(config, new SyncManagerDelegate(this), new NSOperationQueue()));
            }
        }
Exemple #18
0
        private NSUrlSession ConfigureBackgroundSession()
        {
            var configuration = NSUrlSessionConfiguration.BackgroundSessionConfiguration(SessionId);

            if (configuration == null)
            {
                configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(SessionId);
            }

            using (configuration)
            {
                return(NSUrlSession.FromConfiguration(configuration, new BuyplaneAPISessionDelegate(), null));
            }
        }
Exemple #19
0
        void InitializeSession()
        {
            using (var sessionConfig = UIDevice.CurrentDevice.CheckSystemVersion(8, 0)
                                ? NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(sessionId)
                                : NSUrlSessionConfiguration.BackgroundSessionConfiguration(sessionId)) {
                sessionConfig.AllowsCellularAccess = true;

                sessionConfig.NetworkServiceType = NSUrlRequestNetworkServiceType.Default;

                sessionConfig.HttpMaximumConnectionsPerHost = 2;

                var sessionDelegate = new CustomSessionDownloadDelegate(targetFilename);
                this.session = NSUrlSession.FromConfiguration(sessionConfig, sessionDelegate, null);
            }
        }
Exemple #20
0
        NSUrlSession InitBackgroundSession(string identifier)
        {
            LogManager.Shared.Log("Background Session Init");
            Console.WriteLine("InitBackgroundSession");
            configuration = Device.IsIos8
                                        ? NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(identifier)
                                : NSUrlSessionConfiguration.BackgroundSessionConfiguration(identifier);
            configuration.AllowsCellularAccess = true;
            LogManager.Shared.Log(configuration != null ? "Background configuration is null" : "Background configuration created");
            var ses = NSUrlSession.FromConfiguration(configuration, new UrlSessionDelegate(), null);

            ses.GetTasks2((data, upload, downloads) => { restoreTasks(ses, data, upload, downloads); });
            LogManager.Shared.Log("Session created");
            return(ses);
        }
Exemple #21
0
        /// <summary>
        /// Initializes the background session.
        /// </summary>
        /// <returns>The background session.</returns>
        public NSUrlSession InitBackgroundSession()
        {
            // See URL below for configuration options
            // https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionConfiguration_class/index.html

            // Use same identifier for background tasks so in case app terminiated, iOS can resume tasks when app relaunches.
            string identifier = "MyBackgroundTaskId";

            using (var config = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(identifier)) {
                config.HttpMaximumConnectionsPerHost = 4;                 //iOS Default is 4
                config.TimeoutIntervalForRequest     = 600.0;             //30min allowance; iOS default is 60 seconds.
                config.TimeoutIntervalForResource    = 120.0;             //2min; iOS Default is 7 days
                return(NSUrlSession.FromConfiguration(config, new UploadDelegate(), new NSOperationQueue()));
            }
        }
Exemple #22
0
        /**
         * We initialize the background session with the following options
         * - nil as queue: The method, called on events could end up on any thread
         * - Only one connection per host
         */
        NSUrlSession InitBackgroundSession(UrlSessionDownloadDelegate sessionDownloadDelegate)
        {
            sessionDownloadDelegate.Controller = this;

            NSUrlSessionConfiguration configuration;

            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(_identifier);
            }
            else
            {
                configuration = NSUrlSessionConfiguration.BackgroundSessionConfiguration(_identifier);
            }
            return(InitSession(sessionDownloadDelegate, configuration));
        }
Exemple #23
0
        public async Task StartAsync()
        {
            Debug.Assert(this.session == null, "Session already initialized!");

            // Create our view of the world based on the on-disk data structures.
            this.RestoreAllUploadsInWorkDirectory();

            NSUrlSessionConfiguration config;

            if (!string.IsNullOrWhiteSpace(this.SessionIdentifier))
            {
                Console.WriteLine($"Creating background session with identifier '{this.SessionIdentifier}'");
                config = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(this.SessionIdentifier);
            }
            else
            {
                Console.WriteLine("Creating ephemeral session configuration.");
                config = NSUrlSessionConfiguration.EphemeralSessionConfiguration;
            }


            // In our case we don't want any (NSURLCache-level) caching to get in the way
            // of our tests, so we always disable the cache.
            config.RequestCachePolicy = NSUrlRequestCachePolicy.ReloadIgnoringCacheData;
            config.Discretionary      = true;

            this.session = NSUrlSession.FromConfiguration(config, new FileUploadDelegate(this), NSOperationQueue.MainQueue);

            config.Dispose();

            // This is where things get wacky.  From the point that we create the session (in the previous
            // line) to the point where the block passed to -getTasksWithCompletionHandler: runs, we can
            // be getting delegate callbacks for tasks whose corresponding upload objects are in the wrong
            // state (specifically, the task property isn't set and, in some cases, the state might be wrong).
            // A lot of the logic in -syncUploadTasks: and, especially -uploadForTask:, is designed to
            // compensate for that oddity.
            var activeTasks = await this.session.GetTasks2Async();

            var activeUploadTasks = activeTasks.UploadTasks;

            NSOperationQueue.MainQueue.AddOperation(() => {
                this.SyncUploadTasks(activeUploadTasks);
            });

            Console.WriteLine("FileUploadManager did start.");
        }
Exemple #24
0
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            if (session == null)
            {
                var config = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration("test");
                config.SessionSendsLaunchEvents = true;
                config.Discretionary            = true;

                session = NSUrlSession.FromConfiguration(config, this, null);
            }

            downloadTask = session.CreateDownloadTask(new NSUrl("http://rss.art19.com/episodes/439bd7ab-177b-4552-a102-eca19b7e50fd.mp3"));

            downloadTask.Resume();
        }
        /**
         * We initialize the background session with the following options
         * - nil as queue: The method, called on events could end up on any thread
         * - Only one connection per host
         */
        NSUrlSession InitBackgroundSession(UrlSessionDownloadDelegate sessionDownloadDelegate)
        {
            sessionDownloadDelegate.Controller = this;

            NSUrlSessionConfiguration configuration;

            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                using (configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(_identifier)) {
                    return(createSession(configuration, sessionDownloadDelegate));
                }
            }
            else
            {
                using (configuration = NSUrlSessionConfiguration.BackgroundSessionConfiguration(_identifier)) {
                    return(createSession(configuration, sessionDownloadDelegate));
                };
            }
        }
Exemple #26
0
        NSUrlSession CreateUploadSession()
        {
            if (_uploadSession == null)
            {
                string urlSessioinId = Guid.NewGuid().ToString();
                NSUrlSessionConfiguration sessionConfiguration;
                sessionConfiguration = new Version(UIDevice.CurrentDevice.SystemVersion).Major > 7
                    ? NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(urlSessioinId)
                    : NSUrlSessionConfiguration.BackgroundSessionConfiguration(urlSessioinId);
                sessionConfiguration.TimeoutIntervalForRequest  = Timeout;
                sessionConfiguration.TimeoutIntervalForResource = Timeout;

                var uploadDelegate = new NSUrlUploadDelegate(OnUploadCompleted, _behaviors.ReadProgressCallback);

                _uploadSession = NSUrlSession.FromConfiguration(sessionConfiguration, uploadDelegate, new NSOperationQueue());
            }

            return(_uploadSession);
        }
        public ViewController(IntPtr handle) : base(handle)
        {
            _testBkgdDownloadTask              = new TestBkgdDownloadTask();
            _testBkgdLocation                  = new TestBkgdLocationUpdates();
            _testBkgdLocation.LocationUpdated += (object sender,
                                                  LocationUpdatedEventArgs e) =>
            {
                Console.WriteLine(e.Location);
                var latString = e.Location.Coordinate.Latitude.ToString(".00000");
                var lngString = e.Location.Coordinate.Longitude.ToString(".000000");
                LocationLabel.Text = $"{latString} - {lngString}";
            };

            var sessionConfiguration = NSUrlSessionConfiguration
                                       .CreateBackgroundSessionConfiguration("com.monojit.development.session.config");

            _backgroundSession = NSUrlSession.FromConfiguration(sessionConfiguration,
                                                                new BackgroundSessionDelegate(),
                                                                new NSOperationQueue());
        }
        public void Setup()
        {
            var audioSession = AVAudioSession.SharedInstance();

            var error = audioSession.SetCategory(AVAudioSessionCategory.Playback);

            if (error != null)
            {
                Log.Debug($"{error.LocalizedDescription}");
            }
            else
            {
                var homeDirectory = NSHomeDirectoryNative();

                baseDownloadURL = new NSUrl(homeDirectory);

                var backgroundConfiguration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration("HLS-Identifier");

                assetDownloadURLSession = AVAssetDownloadUrlSession.CreateSession(backgroundConfiguration, this, NSOperationQueue.MainQueue);
            }
        }
Exemple #29
0
        NSUrlSessionConfiguration CreateSessionConfiguration(IDictionary <string, string> headers, string identifier, string boundary)
        {
            var sessionConfiguration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(identifier);

            var headerDictionary = new NSMutableDictionary();

            headerDictionary.Add(new NSString("Accept"), new NSString("application/json"));
            headerDictionary.Add(new NSString("Content-Type"), new NSString(string.Format("multipart/form-data; boundary={0}", boundary)));


            if (headers != null)
            {
                foreach (string key in headers.Keys)
                {
                    if (!string.IsNullOrEmpty(headers[key]))
                    {
                        var headerKey = new NSString(key);
                        if (headerDictionary.ContainsKey(new NSString(key)))
                        {
                            headerDictionary[headerKey] = new NSString(headers[key]);
                        }
                        else
                        {
                            headerDictionary.Add(new NSString(key), new NSString(headers[key]));
                        }
                    }
                }
            }


            sessionConfiguration.HttpAdditionalHeaders = headerDictionary;
            sessionConfiguration.AllowsCellularAccess  = true;

            sessionConfiguration.NetworkServiceType        = NSUrlRequestNetworkServiceType.Default;
            sessionConfiguration.TimeoutIntervalForRequest = 30;
            //sessionConfiguration.HttpMaximumConnectionsPerHost=1;
            //sessionConfiguration.Discretionary = true;
            return(sessionConfiguration);
        }
Exemple #30
0
        /// <summary>
        /// Initializes the NSUrl session.
        /// </summary>
        private void InitializeNSUrlSession()
        {
            // Initialize session config. Use a background session to enabled out of process uploads/downloads.
            using (var sessionConfig = UIDevice.CurrentDevice.CheckSystemVersion(8, 0)
                ? NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(SessionId)
                : NSUrlSessionConfiguration.BackgroundSessionConfiguration(SessionId))
            {
                // Allow downloads over cellular network
                sessionConfig.AllowsCellularAccess = true;

                // Give the OS a hint about what we are downloading. This helps iOS to prioritize. For example "Background" is used to download data that was not requested by the user and
                // should be ready if the app gets activated.
                sessionConfig.NetworkServiceType = NSUrlRequestNetworkServiceType.Default;

                // Configure how many downloads to allow at the same time. Set to 1 since we only meed to download one file
                sessionConfig.HttpMaximumConnectionsPerHost = 1;

                // Create a session delegate and the session itself
                // Initialize the session itself with the configuration and a session delegate.
                var sessionDelegate = new DownloadDelegate(this);
                this.session = NSUrlSession.FromConfiguration(sessionConfig, sessionDelegate, null);
            }
        }