有没有人成功使用 AFNetworking 下载更大的文件?这是我现在正在使用的代码:
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dfwPath = [documentsDirectory stringByAppendingPathComponent:@"sync_download.db"];
//Delete the existing one if our last sync was interrupted...
[fm removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:@"sync_download.db"] error:nil];
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setObject:@"sync" forKey:@"app"];
[parameters setObject:@"dl" forKey:@"cmd"];
[parameters setObject:version forKey:@"ver"];
[AFHTTPRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"application/bin"]];
AFMyClient *client = [AFMyClient sharedClient];
NSMutableURLRequest* rq = [client requestWithMethod:@"POST" path:@"myserver/ol.php" parameters:parameters];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:rq];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:dfwPath append:NO];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
NSLog(@"The bytes download: %llu of %llu", totalBytesRead, totalBytesExpectedToRead);
//float percentDone = ((float)((int)totalBytesRead) / (float)((int)totalBytesExpectedToRead));
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Finished downloading: %@", [operation responseString]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error downloading: %@",[error debugDescription]);
}];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];
发生的情况是文件被创建但它始终为零字节,即使正在下载的数量约为 10MB。永远不会达到“setDownloadProgressBlock”,但“setCompletionBlockWithSuccess”是。
这是我在发送下载数据之前在服务器上设置标头的方式:
$data = file_get_contents($filename);
header('Pragma: public');
header('Content-Type: application/bin');
header('Content-Disposition: attachment; filename="'.basename($filename).'";');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.strlen($data));
echo $data;
使用较旧的 ASIHttpRequest 库,这非常有效。因此,如果有人知道发生了什么,我将不胜感激。