Skip to content

Commit

Permalink
Add a new async Sample AsyncDownloadImage
Browse files Browse the repository at this point in the history
The sample uses the new async feature to download, save and display a large image.
  • Loading branch information
bopang authored and pjbeaman committed Jul 24, 2013
1 parent d04f21e commit dc502e8
Show file tree
Hide file tree
Showing 19 changed files with 776 additions and 0 deletions.
32 changes: 32 additions & 0 deletions AsyncDownloadImage/AsyncDownloadImage.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsyncDownloadImage", "AsyncDownloadImage\AsyncDownloadImage.csproj", "{2C14BB0C-822A-4E51-8B64-9AADBAB84812}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|iPhoneSimulator = Debug|iPhoneSimulator
Release|iPhoneSimulator = Release|iPhoneSimulator
Debug|iPhone = Debug|iPhone
Release|iPhone = Release|iPhone
Ad-Hoc|iPhone = Ad-Hoc|iPhone
AppStore|iPhone = AppStore|iPhone
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2C14BB0C-822A-4E51-8B64-9AADBAB84812}.Ad-Hoc|iPhone.ActiveCfg = Ad-Hoc|iPhone
{2C14BB0C-822A-4E51-8B64-9AADBAB84812}.Ad-Hoc|iPhone.Build.0 = Ad-Hoc|iPhone
{2C14BB0C-822A-4E51-8B64-9AADBAB84812}.AppStore|iPhone.ActiveCfg = AppStore|iPhone
{2C14BB0C-822A-4E51-8B64-9AADBAB84812}.AppStore|iPhone.Build.0 = AppStore|iPhone
{2C14BB0C-822A-4E51-8B64-9AADBAB84812}.Debug|iPhone.ActiveCfg = Debug|iPhone
{2C14BB0C-822A-4E51-8B64-9AADBAB84812}.Debug|iPhone.Build.0 = Debug|iPhone
{2C14BB0C-822A-4E51-8B64-9AADBAB84812}.Debug|iPhoneSimulator.ActiveCfg = Debug|iPhoneSimulator
{2C14BB0C-822A-4E51-8B64-9AADBAB84812}.Debug|iPhoneSimulator.Build.0 = Debug|iPhoneSimulator
{2C14BB0C-822A-4E51-8B64-9AADBAB84812}.Release|iPhone.ActiveCfg = Release|iPhone
{2C14BB0C-822A-4E51-8B64-9AADBAB84812}.Release|iPhone.Build.0 = Release|iPhone
{2C14BB0C-822A-4E51-8B64-9AADBAB84812}.Release|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator
{2C14BB0C-822A-4E51-8B64-9AADBAB84812}.Release|iPhoneSimulator.Build.0 = Release|iPhoneSimulator
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
StartupItem = AsyncDownloadImage\AsyncDownloadImage.csproj
EndGlobalSection
EndGlobal
37 changes: 37 additions & 0 deletions AsyncDownloadImage/AsyncDownloadImage/AppDelegate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace AsyncDownloadImage
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
UIWindow window;
AsyncDownloadImageViewController viewController;
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
window = new UIWindow (UIScreen.MainScreen.Bounds);

viewController = new AsyncDownloadImageViewController ();
window.RootViewController = viewController;
window.MakeKeyAndVisible ();

return true;
}
}
}

114 changes: 114 additions & 0 deletions AsyncDownloadImage/AsyncDownloadImage/AsyncDownloadImage.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">iPhoneSimulator</Platform>
<ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{2C14BB0C-822A-4E51-8B64-9AADBAB84812}</ProjectGuid>
<ProjectTypeGuids>{6BC8ED88-2882-458C-8E55-DFD12B67127B};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Exe</OutputType>
<RootNamespace>AsyncDownloadImage</RootNamespace>
<IPhoneResourcePrefix>Resources</IPhoneResourcePrefix>
<AssemblyName>AsyncDownloadImage</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhoneSimulator' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\iPhoneSimulator\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<MtouchLink>None</MtouchLink>
<ConsolePause>false</ConsolePause>
<MtouchDebug>true</MtouchDebug>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhoneSimulator' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\iPhoneSimulator\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<MtouchLink>None</MtouchLink>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhone' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\iPhone\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<MtouchDebug>true</MtouchDebug>
<ConsolePause>false</ConsolePause>
<CodesignKey>iPhone Developer</CodesignKey>
<MtouchI18n />
<MtouchArch>ARMv7</MtouchArch>
<IpaPackageName />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhone' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\iPhone\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodesignKey>iPhone Developer</CodesignKey>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Ad-Hoc|iPhone' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\iPhone\Ad-Hoc</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodesignKey>iPhone Distribution</CodesignKey>
<BuildIpa>true</BuildIpa>
<ConsolePause>false</ConsolePause>
<CodesignProvision>Automatic:AdHoc</CodesignProvision>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'AppStore|iPhone' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\iPhone\AppStore</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodesignKey>iPhone Distribution</CodesignKey>
<ConsolePause>false</ConsolePause>
<CodesignProvision>Automatic:AppStore</CodesignProvision>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
<Reference Include="System.Core" />
<Reference Include="monotouch" />
<Reference Include="System.Net.Http" />
</ItemGroup>
<ItemGroup>
<Folder Include="Resources\" />
</ItemGroup>
<ItemGroup>
<None Include="Info.plist" />
</ItemGroup>
<ItemGroup>
<Compile Include="Main.cs" />
<Compile Include="AppDelegate.cs" />
<Compile Include="AsyncDownloadImageViewController.cs" />
<Compile Include="AsyncDownloadImageViewController.designer.cs">
<DependentUpon>AsyncDownloadImageViewController.cs</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<InterfaceDefinition Include="AsyncDownloadImageViewController.xib" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
<BundleResource Include="Resources\Icon.png" />
<BundleResource Include="Resources\Icon%402x.png" />
<BundleResource Include="Resources\Icon-72.png" />
<BundleResource Include="Resources\Default.png" />
<BundleResource Include="Resources\Default%402x.png" />
<BundleResource Include="Resources\Default-568h%402x.png" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
using System;
using System.IO;
using System.Drawing;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Threading;

using MonoTouch.CoreGraphics;
using MonoTouch.CoreImage;

using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace AsyncDownloadImage
{
public partial class AsyncDownloadImageViewController : UIViewController
{
int clickNumber = 0;
WebClient webClient;
public AsyncDownloadImageViewController () : base ("AsyncDownloadImageViewController", null)
{
}

public override void DidReceiveMemoryWarning ()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning ();

// Release any cached data, images, etc that aren't in use.
}

public override void ViewDidLoad ()
{
base.ViewDidLoad ();

this.clickButton.TouchUpInside += (sender, e) => {
clickNumber++;
this.clickButton.SetTitle( "Click Me:" + clickNumber, UIControlState.Normal);
};

this.downloadButton.TouchUpInside += downloadAsync;

this.downloadProgress.Progress = 0.0f;

}

async void downloadAsync(object sender, System.EventArgs ea)
{
webClient = new WebClient ();
//An large image url
var url = new Uri ("http://photojournal.jpl.nasa.gov/jpeg/PIA15416.jpg");
byte[] bytes = null;


webClient.DownloadProgressChanged += HandleDownloadProgressChanged;

this.downloadButton.SetTitle ("Cancel",UIControlState.Normal);
this.downloadButton.TouchUpInside -= downloadAsync;
this.downloadButton.TouchUpInside += cancelDownload;
infoLabel.Text = "Downloading...";

//Start download data using DownloadDataTaskAsync
try{
bytes = await webClient.DownloadDataTaskAsync(url);
}
catch(TaskCanceledException){
Console.WriteLine ("Task Canceled!");
return;
}
catch(Exception e) {
Console.WriteLine (e.ToString());
return;
}
string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
string localFilename = "downloaded.png";
string localPath = Path.Combine (documentsPath, localFilename);
infoLabel.Text = "Download Complete";

//Save the image using writeAsync
FileStream fs = new FileStream (localPath, FileMode.OpenOrCreate);
await fs.WriteAsync (bytes, 0, bytes.Length);

Console.WriteLine("localPath:"+localPath);


//Resizing image is time costing, using async to avoid blocking the UI thread
UIImage image = null;
SizeF imageViewSize = imageView.Frame.Size;

infoLabel.Text = "Resizing Image...";
await Task.Run( () => { image = UIImage.FromFile(localPath).Scale(imageViewSize); } );
Console.WriteLine ("Loaded!");

imageView.Image = image;

infoLabel.Text = "Click Dowload button to download the image";


this.downloadButton.TouchUpInside -= cancelDownload;
this.downloadButton.TouchUpInside += downloadAsync;
this.downloadButton.SetTitle ("Download", UIControlState.Normal);
this.downloadProgress.Progress = 0.0f;
}



void HandleDownloadProgressChanged (object sender, DownloadProgressChangedEventArgs e)
{
this.downloadProgress.Progress = e.ProgressPercentage / 100.0f;
}

void cancelDownload(object sender, System.EventArgs ea)
{
Console.WriteLine ("Cancel clicked!");
if(webClient!=null)
webClient.CancelAsync ();

webClient.DownloadProgressChanged -= HandleDownloadProgressChanged;

this.downloadButton.TouchUpInside -= cancelDownload;
this.downloadButton.TouchUpInside += downloadAsync;
this.downloadButton.SetTitle ("Download", UIControlState.Normal);
this.downloadProgress.Progress = 0.0f;

new UIAlertView ("Canceled"
, "Download has been canceled."
, null
, "OK"
, null).Show();
infoLabel.Text = "Click Dowload button to download the image";
}


public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
// Return true for supported orientations
return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown);
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit dc502e8

Please sign in to comment.