Skip to content

Instantly share code, notes, and snippets.

@CH3COOH
Created March 22, 2013 09:33
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 CH3COOH/5220036 to your computer and use it in GitHub Desktop.
Save CH3COOH/5220036 to your computer and use it in GitHub Desktop.
NSUrlConnectionクラスを使って文字列を非同期ダウンロードするコードを書いたら結構大変なことになった。
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Net;
using System.IO;
namespace WebRequestSample
{
// これがViewControllerのクラス
public partial class WebRequestSampleViewController : UIViewController
{
// 〜省略
public void DidDownloaded (object sender, EventArgs e)
{
var customDelegate = sender as CustomDelegate;
label.Text = customDelegate.GetResultText();
}
void DownloadUsingNSUrlRequest (object sender, EventArgs e)
{
var downloadedDelegate = new CustomDelegate(this);
var req = new NSUrlRequest(new NSUrl("http://ch3cooh.hatenablog.jp/"));
NSUrlConnection connection = new NSUrlConnection(req, downloadedDelegate);
connection.Start();
}
// 〜省略
}
// NSUrlConnectionを使ったダウンロード中に発生するイベントを受け止めるCustomDelegateクラス
public class CustomDelegate : NSUrlConnectionDelegate
{
public byte[] ResponseData { get; set; }
private long _receivedDataLength { get; set; }
private WebRequestSampleViewController _delegate;
public CustomDelegate(WebRequestSampleViewController viewController)
{
_delegate = viewController;
}
public override void ReceivedResponse (NSUrlConnection connection, NSUrlResponse response)
{
long length = response.ExpectedContentLength;
if (length == -1) {
length = 1* 1024 * 1024;
}
ResponseData = new byte[length];
_receivedDataLength = 0;
}
public override void ReceivedData (NSUrlConnection connection, NSData data)
{
System.Runtime.InteropServices.Marshal.Copy(
data.Bytes, ResponseData, (int)_receivedDataLength, (int)data.Length);
_receivedDataLength += data.Length;
}
public override void FinishedLoading (NSUrlConnection connection)
{
_delegate.DidDownloaded(this, new EventArgs());
}
public string GetResultText()
{
return System.Text.UTF8Encoding.UTF8.GetString(
ResponseData, 0, (int)_receivedDataLength);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment