如果你能够使用AFNetworking库,那就很简单了。您可以发出 HTTP 请求并使用其outputStream
属性将文件下载到您的设备。假设您将下载按钮连接到功能downloadVideoFromURL:withName:
- (void)downloadVideoFromURL:(NSURL*)url withName:(NSString*)videoName
{
//filepath to your app's documents directory
NSString *appDocPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *videosPath = [appDocPath stringByAppendingPathComponent:@"Videos"];
NSString *filePath = [videosPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4", videoName]];
//check to make sure video hasn't been downloaded already
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
//file was already downloaded
}
//video wasn't downloaded, so continue
else
{
//enable the network activity indicator
[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
//create a temporary filepath while downloading
NSString *tmpPath = [videosPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-tmp.mp4", videoName]];
//the outputStream property is the key to downloading the file
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:tmpPath append:NO];
//if operation is completed successfully, do following
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//rename the downloaded video to its proper name
[[NSFileManager defaultManager] moveItemAtPath:tmpPath toPath:filePath error:nil];
//disable network activity indicator
[AFNetworkActivityIndicatorManager sharedManager].enabled = NO;
//optionally, post a notification to anyone listening that the download was successful
[[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadedVideo" object:nil];
//if the operation fails, do the following:
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@", error);
//delete the downloaded file (it is probably partially downloaded or corrupt)
[[NSFileManager defaultManager] removeItemAtPath:tmpPath error:nil];
//disable network activity indicator
[AFNetworkActivityIndicatorManager sharedManager].enabled = NO;
}];
//start the operation
[operation start];
}
}