1

次のように宣言された ViewController があります。

@interface DownloadViewController : UIViewController 
           <UITableViewDataSource, UITableViewDelegate>

NSURLConnectionを使用してファイルをダウンロードしたいと考えています。NSURLConnection は単純に「開始しない」ため、デリゲート メソッドは機能しません (たとえば、connection:didReceiveResponseが呼び出されることはありません)。一部のサンプル コードで、クラスがNSObjectではなくサブクラス化されていることに気づきましたUIViewController

どのように組み合わせるのですか?ViewController メソッドを使用したいのですが、NSURLConnectionを使用できません。

NSURLConnection を使用してファイルをダウンロードする方法について完全に説明された例を見つけるのはそれほど簡単ではありません。誰もがdidReceiveResponseのような簡単なメソッドだけに集中します。

4

3 に答える 3

3

問題が発生した場合は、評価の高い ASIHTTPRequest ライブラリを使用してダウンロードを管理することを検討してください。それはあなたのためにすべてを世話します。

たとえば、たった2行でそれができます。

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:fullPathOfWhereToStoreFile];
于 2011-04-27T12:02:46.387 に答える
3

ここでは、NSObject の代わりに UIViewController を使用しても問題ありません。問題なく UIViewController で NSURLConnection を使用しています! これが私のコードの一部です(そのままコンパイルされるかどうかはわかりません):

//
//  MyViewController.h
//

#import <Foundation/Foundation.h>

@interface MyViewController : UIViewController {
    @protected
    NSMutableURLRequest* req;
    NSMutableData* _responseData;
    NSURLConnection* nzbConnection;
}

- (void)loadFileAtURL:(NSURL *)url;

@end

-

//
//  MyViewController.m
//

#import "MyViewController.h"

@implementation MyViewController

- (void)loadView {  
// create your view here
}

- (void) dealloc {
    [_responseData release];

    [super dealloc];
}

#pragma mark -

- (void)loadFileAtURL:(NSURL *)url {
    // allocate data buffer
    _responseData = [[NSMutableData alloc] init];

    // create URLRequest
    req = [[NSMutableURLRequest alloc] init];
    [req setURL:_urlToHandle];

    nzbConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
    [req release];
    req = nil;
}


#pragma mark -

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append data in the reception buffer
    if (connection == nzbConnection)
        [_responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if (connection == nzbConnection) {
        [nzbConnection release];
        nzbConnection = nil;

        // Print received data
        NSLog(@"%@",_responseData);

        [_responseData release];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // Something went wrong ...
    if (connection == nzbConnection) {
        [nzbConnection release];
        [_responseData release];
    }
}

@end

大きなファイルをダウンロードする場合は、受信したパケットをメモリに保存するのではなく、ファイルに保存することを検討してください。

于 2011-04-27T15:31:09.903 に答える
1

「NSURLConnection非同期」検索を使用して用語を検索すると、ソースが見つかります。または単に NSURLConnection です。

例えば:

非同期 Web サービス呼び出し用の NSURLConnection NSURLRequest プロキシ

サンプルコードでAppleのNSURLConnectionを使用する

Objective-C プログラミング チュートリアル – Twitter クライアントの作成パート 1

于 2011-04-27T12:00:49.520 に答える