Created
March 22, 2013 09:33
-
-
Save CH3COOH/5220036 to your computer and use it in GitHub Desktop.
NSUrlConnectionクラスを使って文字列を非同期ダウンロードするコードを書いたら結構大変なことになった。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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