0

I am using AFNetworking to download an mp3 file. The download happens in a particular ViewController. Since the mp3 file is quite large, it takes a few minutes to complete the download. The problem is that when i go to another ViewController, the download stops and i have to stay on the download ViewController and wait for the download to complete. That would be frustrating for the user! Is there a way to get the download going even when the download ViewController is dismissed? Here is the code i use for downloading:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.sample.com/samplefile.mp3"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSString *mp3Name = @"sample.mp3";

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:mp3Name];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Successfully downloaded file to %@", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
4

2 回答 2

0

您可以创建单例

 +(id)sharedInstance
{
static dispatch_once_t pred;
static MyClass *sharedInstance = nil;
dispatch_once(&pred, ^{
    sharedInstance = [[MyClass alloc] init];
});
return sharedInstance;
}

并在其中实现您的下载操作。

如果您在阅读这篇文章iOS 设计模式之前没有使用过单调

另请阅读有关 raywenderlich 的这篇文章。它将让您了解如何正确地组织使用 Web 服务的工作

AFNetworking 速成班

NSOperations

于 2014-02-15T16:43:31.060 回答
0

实现您想要的最简单的方法是在 ApplicationDelegate 中放置一个方法,该方法开始下载并在下载完成后通知您的视图控制器。因此,只需将您的代码移动到 applicationDelegate。

请注意:我认为这不是最好的方法,最好在一个单独的类中处理网络流量,但最简单的方法是使用(已经建立的)单例,即您的 ApplicationDelegate。

于 2014-02-15T16:49:19.730 回答