예제 #1
0
        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 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");
                }
        }
예제 #3
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);
            }
        }
예제 #4
0
 static NSUrlSession InitBackgroundSession()
 {
     Console.WriteLine("InitBackgroundSession");
     using (var configuration = NSUrlSessionConfiguration.BackgroundSessionConfiguration("async.background.downloader")) {
         return(NSUrlSession.FromConfiguration(configuration, new UrlSessionDelegate(), null));
     }
 }
예제 #5
0
        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();
            //    }
            //});
        }
예제 #6
0
        public NSUrlSessionHandler(NSUrlSessionConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            AllowAutoRedirect = true;

            // we cannot do a bitmask but we can set the minimum based on ServicePointManager.SecurityProtocol minimum
            var sp = ServicePointManager.SecurityProtocol;

            if ((sp & SecurityProtocolType.Ssl3) != 0)
            {
                configuration.TLSMinimumSupportedProtocol = SslProtocol.Ssl_3_0;
            }
            else if ((sp & SecurityProtocolType.Tls) != 0)
            {
                configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_0;
            }
            else if ((sp & SecurityProtocolType.Tls11) != 0)
            {
                configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_1;
            }
            else if ((sp & SecurityProtocolType.Tls12) != 0)
            {
                configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_2;
            }

            session          = NSUrlSession.FromConfiguration(configuration, (INSUrlSessionDelegate) new NSUrlSessionHandlerDelegate(this), null);
            inflightRequests = new Dictionary <NSUrlSessionTask, InflightData> ();
        }
        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();
                }
            });
        }
예제 #8
0
 public NSUrlSession InitBackgroundSession()
 {
     Console.WriteLine("InitBackgroundSession");
     using (var configuration = NSUrlSessionConfiguration.BackgroundSessionConfiguration(Identifier)) {
         return(NSUrlSession.FromConfiguration(configuration, new UrlSessionDelegate(this), null));
     }
 }
예제 #9
0
        public void HandleBackgroundTasks(NSSet <WKRefreshBackgroundTask> backgroundTasks)
        {
            foreach (WKRefreshBackgroundTask task in backgroundTasks)
            {
                Console.WriteLine($"received background task: {task}");
                // only handle these while running in the background

                if (WKExtension.SharedExtension.ApplicationState == WKApplicationState.Background)
                {
                    if (task is WKApplicationRefreshBackgroundTask)
                    {
                        // this task is completed below, our app will then suspend while the download session runs
                        Console.WriteLine("application task received, start URL session");
                        ScheduleURLSession();
                    }
                }
                else if (task is WKUrlSessionRefreshBackgroundTask)
                {
                    var backgroundConfigObject = NSUrlSessionConfiguration.BackgroundSessionConfiguration(((WKUrlSessionRefreshBackgroundTask)task).SessionIdentifier);
                    var backgroundSession      = NSUrlSession.FromWeakConfiguration(backgroundConfigObject, this, null);
                    Console.WriteLine($"Rejoining session {backgroundSession}");
                }

                task.SetTaskCompleted();
            }
        }
예제 #10
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);
            });
        }
예제 #11
0
        public AssetPersistenceManager()
        {
            var backgroundConfiguration = NSUrlSessionConfiguration.BackgroundSessionConfiguration("AAPL-Identifier");

            assetDownloadUrlSession = AVAssetDownloadUrlSession.CreateSession(backgroundConfiguration, this, NSOperationQueue.MainQueue);
            activeDownloadsMap      = new Dictionary <AVAggregateAssetDownloadTask, Asset>();
            willDownloadToUrlMap    = new Dictionary <AVAggregateAssetDownloadTask, NSUrl>();
        }
예제 #12
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
        }
예제 #13
0
        public NSUrlSession InitBackgroundSession()
        {
            Console.WriteLine("InitBackgroundSession");

            using (var configuration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(Identifier))
            {
                return(NSUrlSession.FromConfiguration(configuration, new UrlSessionDelegate(GuitarListViewController), null));
            }
        }
예제 #14
0
        public void BackgroundSessionConfiguration()
        {
            TestRuntime.AssertXcodeVersion(5, 0);

            // https://trello.com/c/F6cyUBFU/70-simple-background-transfer-bo-pang-block-by-an-system-invalidcastexception-in-nsurlsessionconfiguration-backgroundsessionconfigu
            using (var session = NSUrlSessionConfiguration.BackgroundSessionConfiguration("id")) {
                Assert.That(session.Identifier, Is.EqualTo("id"), "Identifier");
            }
        }
 public void Init(string sessionId, string url, TransferTaskMode mode)
 {
     using (var configuration = NSUrlSessionConfiguration.BackgroundSessionConfiguration(sessionId))
     {
         _mode      = mode;
         _sessionId = sessionId;
         _url       = url;
         session    = NSUrlSession.FromConfiguration(configuration);
     }
 }
예제 #16
0
        NSUrlSession InitSession(UrlSessionDownloadDelegate sessionDownloadDelegate,
                                 NSUrlSessionConfiguration configuration)
        {
            sessionDownloadDelegate.Controller = this;

            using (configuration)
            {
                return(createSession(configuration, sessionDownloadDelegate));
            }
        }
예제 #17
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));
        }
예제 #18
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();
        }
        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));
            }
        }
        public void BackgroundSessionConfiguration()
        {
            if (!TestRuntime.CheckSystemAndSDKVersion(7, 0))
            {
                Assert.Inconclusive("requires iOS7");
            }

            // https://trello.com/c/F6cyUBFU/70-simple-background-transfer-bo-pang-block-by-an-system-invalidcastexception-in-nsurlsessionconfiguration-backgroundsessionconfigu
            using (var session = NSUrlSessionConfiguration.BackgroundSessionConfiguration("id")) {
                Assert.That(session.Identifier, Is.EqualTo("id"), "Identifier");
            }
        }
예제 #21
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);
        }
        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);
        }
예제 #23
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;
        }
 /// <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);
     }
 }
예제 #25
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");
            }
        }
예제 #26
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()));
            }
        }
예제 #27
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));
            }
        }
예제 #28
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);
        }
예제 #29
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()));
            }
        }
예제 #30
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);
            }
        }
예제 #31
0
 public static new NSUrlSession FromConfiguration(NSUrlSessionConfiguration configuration)
 {
     throw new NotSupportedException ("NS_UNAVAILABLE");
 }
예제 #32
0
 public static new NSUrlSession FromWeakConfiguration(NSUrlSessionConfiguration configuration, NSObject weakDelegate, NSOperationQueue delegateQueue)
 {
     throw new NotSupportedException ("NS_UNAVAILABLE");
 }