在objective-c中暂停下载

时间:2014-09-02 19:53:27

标签: ios objective-c

我不确定暂停下载的最佳方法是什么。我之前已经在堆栈上看过这个问题,但似乎没有达到我想要的结果。例如:我理解AppDelegate内部,如果手机上有电话,则会调用 - (void)applicationWillResignActive:(UIApplication *)application。我的应用程序成功下载数据库以正常运行至关重要。这是我用来下载数据库的代码:

NSString * urlDb = [NSString stringWithFormat:@" someURl'];

//---Create URL from where DB has to be download-----
NSURL *url = [NSURL URLWithString:urlDb];

NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];

暂停下载可能并不重要,例如AT& T,但是Verizon的用户无法同时进行通话和下载。任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

如果您想要暂停/恢复功能,那么您必须使用旧的NSURLConnection,并实现所有必需的委托方法,或者您可以使用新的NSURLSession API。 以下是NSURLConnection的基本实现:

@property NSFileHandle *fileHandle;
@property NSURLConnection *connection;

// start download

- (IBAction)downloadButtonPressed
{
    NSURL *url = [NSURL URLWithString:@"myUrl"];
    NSURLRequest *dataRequest = [NSURLRequest requestWithURL:url];
    self.connection = [NSURLConnection connectionWithRequest:dataRequest delegate:self];
    [connection start];
}

实施委托方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:@“pathToYourFile”];
    [self.fileHandle seekToEndOfFile];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.fileHandle writeData:data];
}

如果你想暂停 - 只需取消这样的连接:

[self.connection cancel];

然后你可以这样恢复:

- (void)resumeDownload
{
    NSURL *url = [NSURL URLWithString:@"myUrl"];
    NSMutableURLRequest *dataRequest = [NSMutableURLRequest requestWithURL:url];
    NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:pathToYourFile error:&attributesError];
    NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
    NSString *bytesRangeHeader = [NSString stringWithFormat:@"bytes=%lld-", [fileSizeNumber longLongValue];
    [_request setValue:bytesRangeHeader forHTTPHeaderField:@"Range"];
    self.connection = [NSURLConnection connectionWithRequest:dataRequest delegate:self];
    [connection start];
}