Forum Xamarin.Forms

Download file in background.

shtpavelshtpavel UAMember

Hello guys,

is there any way to unified way to start some download tasks in background in xamarin forms? And download to local storage.

Thanks!

Best Answer

Answers

  • RafaelMouraRafaelMoura BRInsider, University, Developer Group Leader ✭✭✭

    Hello
    See https://github.com/Xamarin-Student-Ambassadors/DownloadManager-plugin-for-Xamarin.Forms

    I create this plugin, its work, but nuget have a problem.

    Try implement :)

    Dependecy Service ;)

  • shtpavelshtpavel UAMember

    @RafaelMoura Oh it's great, but I want to create some kind of download queue run in background.

  • RafaelMouraRafaelMoura BRInsider, University, Developer Group Leader ✭✭✭

    Android use native DownloadManager.

    Windows phone 8.1 use BackgroundDownloader .

    iOS u need use WebClient, but u can do Background with async and queue it :)

    Windows phone 8 use BackgroundTransferRequest with queue

    code here

    public void Download(string uri, string fileName, string authHeader)
            {
    
                string transferFileName = fileName;
                Uri transferUri = new Uri(uri);
    
    
                // Create the new transfer request, passing in the URI of the file to 
                // be transferred.
                BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
    
                // Set the transfer method. GET and POST are supported.
                transferRequest.Method = "GET";
    
                transferRequest.Headers.Add("Authorization", "Basic " + authHeader);
    
                // Get the file name from the end of the transfer URI and create a local URI 
                // in the "transfers" directory in isolated storage.
                string downloadFile = transferFileName.Substring(transferFileName.LastIndexOf("/") + 1);
                Uri downloadUri = new Uri("shared/transfers/" + downloadFile, UriKind.RelativeOrAbsolute);
                transferRequest.DownloadLocation = downloadUri;
    
                // Pass custom data with the Tag property. In this example, the friendly name
                // is passed.
                transferRequest.Tag = downloadFile;
    
                transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
    
    
                try
                {
                    BackgroundTransferService.Add(transferRequest);
    
                    transferRequest.TransferStatusChanged += transferRequest_TransferStatusChanged;
    
                }
                catch (InvalidOperationException ex)
                {
                    MessageBox.Show("Não foi possível iniciar o download. " + ex.Message);
                }
                catch (Exception)
                {
                    MessageBox.Show("Não foi possível iniciar o download. Erro generico.");
                }
            }
    
            private void transferRequest_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
            {
    
                BackgroundTransferRequest transfer = sender as BackgroundTransferRequest;
    
                switch (transfer.TransferStatus)
                {
                    case TransferStatus.Completed:
    
                        // If the status code of a completed transfer is 200 or 206, the
                        // transfer was successful
                        if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
                        {
                            // Remove the transfer request in order to make room in the 
                            // queue for more transfers. Transfers are not automatically
                            // removed by the system.
                            BackgroundTransferService.Remove(transfer);
    
                            // In this example, the downloaded file is moved into the root
                            // Isolated Storage directory
                            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                            {
                                string filename = transfer.Tag;
                                if (isoStore.FileExists(filename))
                                {
                                    isoStore.DeleteFile(filename);
                                }
                                isoStore.MoveFile(transfer.DownloadLocation.OriginalString, filename);
    
                                MessageBox.Show("Download feito, arquivo salvo. Nome: " + filename);
                            }
    
    
                        }
                        else
                        {
                            // This is where you can handle whatever error is indicated by the
                            // StatusCode and then remove the transfer from the queue. 
                            BackgroundTransferService.Remove(transfer);
    
                            if (transfer.TransferError != null)
                            {
                                // Handle TransferError if one exists.
                            }
                        }
                        break;
    
    
                    case TransferStatus.WaitingForExternalPower:
                        MessageBox.Show("Pouca bateria, conecte o celular em uma tomada para continuar o download.");
                        break;
    
                    case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode:
                        MessageBox.Show("Modo de economia de energia, desabilite ou conecte o celular em uma tomada.");
                        break;
    
                    case TransferStatus.WaitingForNonVoiceBlockingNetwork:
                        MessageBox.Show("Chamada de voz ativa, aguardando.");
                        break;
    
                    case TransferStatus.WaitingForWiFi:
                        MessageBox.Show("Aguardando sinal WiFi.");
                        break;
                }
            }
    
  • MirkoMMirkoM USMember ✭✭

    @RafaelMoura said:
    Hello
    See https://github.com/Xamarin-Student-Ambassadors/DownloadManager-plugin-for-Xamarin.Forms

    I create this plugin, its work, but nuget have a problem.

    Try implement :)

    Dependecy Service ;)

    New link: https://github.com/logikonline/download-manager-plugin

Sign In or Register to comment.