Skip to content

Instantly share code, notes, and snippets.

@Cheesebaron
Created February 18, 2015 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cheesebaron/d622feba376381ba1b53 to your computer and use it in GitHub Desktop.
Save Cheesebaron/d622feba376381ba1b53 to your computer and use it in GitHub Desktop.
iOS Background Tasks
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Foundation;
using ModernHttpClient;
using UIKit;
namespace App6
{
[Register("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
UIWindow _window;
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
// create a new window instance based on the screen size
_window = new UIWindow(UIScreen.MainScreen.Bounds);
_window.MakeKeyAndVisible();
app.RegisterUserNotificationSettings(
UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Badge | UIUserNotificationType.Alert, null));
return true;
}
private CancellationTokenSource _cancellationTokenSource;
public override async void DidEnterBackground(UIApplication application)
{
var taskId = UIApplication.SharedApplication.BeginBackgroundTask(BackgroundTimeExpired);
_cancellationTokenSource = new CancellationTokenSource();
try
{
await TransferAsync(50, _cancellationTokenSource.Token);
}
catch (OperationCanceledException) {}
catch (AggregateException) { }
UIApplication.SharedApplication.EndBackgroundTask(taskId);
}
private void BackgroundTimeExpired()
{
if (_stopwatch.IsRunning)
_stopwatch.Stop();
_cancellationTokenSource.Cancel();
var notification = new UILocalNotification
{
AlertAction = "Background Transfer",
AlertBody = string.Format("Background Time Expired after: {0:mm} minutes", _stopwatch.Elapsed)
};
UIApplication.SharedApplication.PresentLocalNotificationNow(notification);
}
private Stopwatch _stopwatch;
private int _iteration;
private async Task TransferAsync(int iterations, CancellationToken token)
{
token.ThrowIfCancellationRequested();
var url = "https://github.com/paulcbetts/ModernHttpClient/releases/download/2.2.0/ModernHttpClient-2.2.0.zip";
var handler = new NativeMessageHandler();
var client = new HttpClient(handler);
_iteration = 0;
_stopwatch = new Stopwatch();
_stopwatch.Start();
while (!token.IsCancellationRequested && _iteration < iterations)
{
var bytesRead = 0;
try
{
using(var request = new HttpRequestMessage(HttpMethod.Get, url))
using (var resp =
await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token))
{
var bytes = await resp.Content.ReadAsByteArrayAsync();
bytesRead = bytes.Length;
bytes = null;
}
}
catch { }
PresentNotification(_iteration, bytesRead);
_iteration++;
await Task.Delay(6000, token);
}
_stopwatch.Stop();
}
private static void PresentNotification(int iteration, int bytesRead)
{
var notification = new UILocalNotification {
AlertAction = "Background Transfer",
AlertBody = string.Format("Fetched file: {0}, Bytes: {1}", iteration, bytesRead),
ApplicationIconBadgeNumber = iteration
};
UIApplication.SharedApplication.PresentLocalNotificationNow(notification);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment