web-dev-qa-db-ja.com

AFNetworking-AFHTTPRequestOperationを使用してファイルをダウンロードしますか?

男、これに困惑した。 AFNetworking を使用してファイルをダウンロードしようとすると、downloadProgressBlockで進行状況バイトをキャプチャするのが最善の方法です。 AFNetworkingのさまざまなフォークを試しましたが、最新のビルドに戻りました。かつてAFHTTPRequestOperationがNSURLResponseも含むように変更されたように見えますが、最新のリリースでは削除されています。また、以下のコードによると、「success」ブロックが呼び出されることはありません。ダウンロードしたバイトのログを取得すると、^ completeが呼び出されます。成功とエラーが呼び出されることはありません。

これに関するガイダンスは素晴らしいでしょう。データが返される場所と、NSFileManagerを使用するためのデータの取得方法がわかりません。画像などのストリームを書き込むのではなく、ファイルをダウンロードする必要があります。

編集:ドキュメントで提案されているように、 void)connection:didReceiveDataをオーバーライドしてデータをキャプチャしようとしましたが、何もしていません。

// URLは---(http://mydomain.com/somezip.Zip

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", url]]];

AFHTTPRequestOperation *operation = [AFHTTPRequestOperation HTTPRequestOperationWithRequest:request success:^(id object) {

    NSLog(@"hey, some success!");

} failure:^(NSHTTPURLResponse *response, NSError *error) {

    NSLog(@"%@", error);

}];


[operation setDownloadProgressBlock:^(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead) {

    // callback is sent in and works great.  Just outputting to the console at the moment
    SEL callme = NSSelectorFromString(callback);
    [sender performSelectorOnMainThread:callme withObject:[NSNumber numberWithInt:bytesRead] waitUntilDone:NO];

}];

[operation setCompletionBlock:^{
    NSLog(@"operation complete");
}];

NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
16
Bat Lanyard

AFNetworkingに含まれているこの機能を使用して、ディスクに保存することもできます-operation.outputStreamに注意してください。

NSMutableURLRequest* rq = [api requestWithMethod:@"GET" path:@"YOUR/URL/TO/FILE" parameters:nil];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:rq] autorelease];

NSString* path=[@"/PATH/TO/APP" stringByAppendingPathComponent: imageNameToDisk];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSLog(@"SUCCCESSFULL IMG RETRIEVE to %@!",path)

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    // Deal with failure
}];

[〜#〜] edit [〜#〜]missed

[operation start]; 

[〜#〜] edit [〜#〜]...or if you use an AFHTTPClient * apiClient :

// [apiClient enqueueHTTPRequestOperation:operation];
64
Carlos Ricardo