Exemplo n.º 1
0
 public NSUrlSession InitBackgroundSession()
 {
     Console.WriteLine("InitBackgroundSession");
     using (var configuration = NSUrlSessionConfiguration.BackgroundSessionConfiguration(Identifier)) {
         return(NSUrlSession.FromConfiguration(configuration, new UrlSessionDelegate(this), null));
     }
 }
Exemplo n.º 2
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();
            }
        }
Exemplo n.º 3
0
 static NSUrlSession InitBackgroundSession()
 {
     Console.WriteLine("InitBackgroundSession");
     using (var configuration = NSUrlSessionConfiguration.BackgroundSessionConfiguration("async.background.downloader")) {
         return(NSUrlSession.FromConfiguration(configuration, new UrlSessionDelegate(), null));
     }
 }
Exemplo n.º 4
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);
            }
        }
Exemplo n.º 5
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>();
        }
Exemplo n.º 6
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);
     }
 }
        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");
            }
        }
        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);
     }
 }
Exemplo n.º 11
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));
            }
        }
Exemplo n.º 12
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);
            }
        }
Exemplo n.º 13
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);
        }
Exemplo n.º 14
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));
        }
Exemplo n.º 15
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);
        }
        /**
         * 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));
                };
            }
        }
Exemplo n.º 17
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);
            }
        }
Exemplo n.º 18
0
        NSUrlSession CreateDownloadSession()
        {
            if (_downloadSession == null)
            {
                string urlSessioinId = Guid.NewGuid().ToString();
                NSUrlSessionConfiguration sessionConfiguration;
                if (new Version(UIDevice.CurrentDevice.SystemVersion).Major > 7)
                {
                    sessionConfiguration = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(urlSessioinId);
                }
                else
                {
                    sessionConfiguration = NSUrlSessionConfiguration.BackgroundSessionConfiguration(urlSessioinId);
                }
                sessionConfiguration.TimeoutIntervalForRequest  = TIMEOUT;
                sessionConfiguration.TimeoutIntervalForResource = TIMEOUT;

                NSUrlDownloadDelegate downloadDelegate = new NSUrlDownloadDelegate(OnDownloadCompleted, OnProgress);

                _downloadSession = NSUrlSession.FromConfiguration(sessionConfiguration, downloadDelegate, new NSOperationQueue());
            }

            return(_downloadSession);
        }
Exemplo n.º 19
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            this.Title = "Downloads";

            // Add a bar button item to exit the app manually. Don't do this in productive apps - Apple won't approve it!
            // We have it here to demonstrate that iOS will relaunch the app if a download has finished.
            this.NavigationItem.LeftBarButtonItem = new UIBarButtonItem("Quit", UIBarButtonItemStyle.Plain, delegate {
                // Store all download info to disk. If iOS terminates the app, this would be handled in WillTerminate().
                // However this won't be triggered if the app is killed manually by this call.
                AppDelegate.SerializeAvailableDownloads();

                // Exit application with code 3.
                FileTransferController.Exit(3);
            });


            // Add a bar button item to reset all downloads.
            var refreshBtn = new UIBarButtonItem(UIBarButtonSystemItem.Refresh);

            refreshBtn.Clicked += async(sender, e) => {
                var pendingTasks = await this.Session.GetTasksAsync();

                if (pendingTasks != null && pendingTasks.DownloadTasks != null)
                {
                    foreach (var task in pendingTasks.DownloadTasks)
                    {
                        task.Cancel();
                    }
                }

                AppDelegate.AvailableDownloads.ForEach(info => {
                    if (info.DestinationFile != null)
                    {
                        try
                        {
                            File.Delete(info.DestinationFile.Path);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Failed to delete '{0}': {1}", info.DestinationFile, ex);
                        }
                    }

                    info.Reset();
                    info.Status = DownloadInfo.STATUS.Idle;
                });

                AppDelegate.ResetAvailableDownloads();
                ((DelegateTableViewSource <DownloadInfo>)(this.TableView.Source)).Items = AppDelegate.AvailableDownloads;

                this.TableView.ReloadData();

                AppDelegate.SerializeAvailableDownloads();
            };
            this.NavigationItem.RightBarButtonItem = refreshBtn;


            // TODO: FileTransfer 01 - Create a session
            // 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;

                // We want our app to be launched if required.
                sessionConfig.SessionSendsLaunchEvents = 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;

                // TODO: FileTransfer 02 - Create a session delegate and the session itself
                // Initialize the session itself with the configuration and a session delegate.
                var sessionDelegate = new SessionDelegate(this);
                this.Session = NSUrlSession.FromConfiguration(sessionConfig, sessionDelegate, null);
            }

            // Create a source for the table view.
            var source = new DelegateTableViewSource <DownloadInfo> (this.TableView, "downloaderCellId")
            {
                Items       = AppDelegate.AvailableDownloads,
                GetCellFunc = (info, cell) =>
                {
                    var downloaderCell = (DownloaderCell)cell;
                    downloaderCell.UpdateFromDownloadInfo(info);
                    return(downloaderCell);
                },
                RowSelectedFunc = info =>
                {
                    if (info.Status == DownloadInfo.STATUS.Completed)
                    {
                        var previewController = UIDocumentInteractionController.FromUrl(info.DestinationFile);
                        previewController.Delegate = new PreviewDelegate(this);
                        previewController.PresentPreview(true);
                    }
                }
            };

            this.TableView.RowHeight = 55;
            this.TableView.Source    = source;

            // Trigger a delegate if the user taps a button of a cell.
            DownloaderCell.ActionRequested = this.HandleActionRequested;
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Add a bar button item to exit the app manually. Don't do this in productive apps - Apple won't approve it!
            // We have it here to demonstrate that iOS will relaunch the app if a download has finished.
            this.NavigationItem.LeftBarButtonItem = new UIBarButtonItem("Quit", UIBarButtonItemStyle.Plain, delegate {
                // Store all download info to disk. If iOS terminates the app, this would be handled in WillTerminate().
                // However this won't be triggered if the app is killed manually by this call.
                AppDelegate.SerializeAvailableDownloads();

                // Exit application with code 3.
                MusicListController.Exit(3);
            });

            // Magic line: allows starting music playback when app is backgrounded or even terminated!
            UIApplication.SharedApplication.BeginReceivingRemoteControlEvents();

            // We must set up an AVAudioSession and tell iOS we want to playback audio. Only then can music playback be used in the background.
            var audioSession = AVAudioSession.SharedInstance();

            audioSession.SetCategory(AVAudioSessionCategory.Playback);
            audioSession.SetActive(true);

            // Add a bar button item to reset all downloads.
            var refreshBtn = new UIBarButtonItem(UIBarButtonSystemItem.Refresh);

            refreshBtn.Clicked += async(sender, e) => {
                // Stop audio.
                this.PlayAudio(null);

                var pendingTasks = await this.Session.GetTasks2Async();

                if (pendingTasks != null && pendingTasks.DownloadTasks != null)
                {
                    foreach (var task in pendingTasks.DownloadTasks)
                    {
                        task.Cancel();
                    }
                }

                AppDelegate.AvailableDownloads.ForEach(info => info.Reset(true));

                AppDelegate.ResetAvailableDownloads();
                ((DelegateTableViewSource <DownloadInfo>)(this.TableView.Source)).Items = AppDelegate.AvailableDownloads;

                this.TableView.ReloadData();

                AppDelegate.SerializeAvailableDownloads();
            };


            // Add a button to stops playback.
            this.stopBtn = new UIBarButtonItem(UIBarButtonSystemItem.Stop)
            {
                Enabled = false
            };
            this.stopBtn.Clicked += (sender, e) => this.StopAudio();

            this.NavigationItem.RightBarButtonItems = new UIBarButtonItem[] { refreshBtn, this.stopBtn };


            // 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;

                // We want our app to be launched if required.
                //sessionConfig.SessionSendsLaunchEvents = 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 SessionDelegate(this);
                this.Session = NSUrlSession.FromConfiguration(sessionConfig, (INSUrlSessionDelegate)sessionDelegate, null);
            }

            this.TableView.Source = new DelegateTableViewSource <DownloadInfo>(this.TableView, "MUSIC_CELL")
            {
                Items       = AppDelegate.AvailableDownloads,
                GetCellFunc = (item, cell) =>
                {
                    var musicCell = (MusicCell)cell;
                    musicCell.InitFromDownloadInfo(item);
                    return(musicCell);
                },
                RowSelectedFunc = (downloadInfo, cell, indexPath) =>
                {
                    // If a row gets tapped, download or play.
                    if (downloadInfo.Status != DownloadInfo.STATUS.Completed & downloadInfo.Status != DownloadInfo.STATUS.Downloading)
                    {
                        // Queue download.
                        this.EnqueueDownloadAsync(downloadInfo);

                        // Update UI once more. Download initialization might have failed	.
                        ((MusicCell)cell).InitFromDownloadInfo(downloadInfo);

                        this.TableView.ReloadRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.None);
                    }
                    else if (downloadInfo.Status == DownloadInfo.STATUS.Completed)
                    {
                        // Play MP3.
                        this.currentSongIndex = indexPath.Row;
                        this.PlayAudio(downloadInfo);
                    }
                }
            };

            this.TableView.EstimatedRowHeight = 100;
            this.TableView.RowHeight          = UITableView.AutomaticDimension;
        }