ios - 如何在 iOS 中以进度在后台下载多个 mp4 文件?
<p><p>我在这个问题上坚持了两天。请帮帮我。 </p>
<p>我的要求是,如果我在第二个 ViewController 的后台下载文件并且在下载开始后我弹出到第一个 ViewController 并且如果我再次推送到第二个 ViewController ,那么应该继续该进度。 </p>
<p>这里发生了什么:</p>
<ol>
<li>我推送到第二个 ViewController 。</li>
<li>我使用 <code>NSMutableURLRequest</code>、<code>NSURLConnection</code> 开始下载。 </li>
<li>如果我弹出到第一个 ViewController 并再次转到第二个 ViewController ,则所有 View 都显示为 0。意味着如果在弹出期间进度为 34%,然后再次推送时间,它的 0% 显示在我的 UI 中,但下载照常继续。 </li>
</ol>
<p>我的日志也显示完美,但 UI 没有显示。我尝试了所有的答案。都是同一个问题。</p>
<p>这是我的全部代码:</p>
<p>应用内委托(delegate)方法:</p>
<h1>CTAppDelegate.h</h1>
<pre><code>@property (copy) void (^backgroundSessionCompletionHandler)();
</code></pre>
<h1>CTAppDelegate.m</h1>
<pre><code>- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
{
self.backgroundSessionCompletionHandler = completionHandler;
}
</code></pre>
<h1>2ndViewController.h</h1>
<pre><code>- (IBAction)downloadBackground:(id)sender;
- (IBAction)downloadImage:(id)sender;
@property (strong, nonatomic) IBOutlet UIImageView *downloadedImage;
@property (strong, nonatomic) IBOutlet UIProgressView *progressView;
@end
</code></pre>
<h1>2ndViewController.m</h1>
<pre><code>#import "CTViewController.h"
#import "CTSessionOperation.h"
#import "CTAppDelegate.h"
static NSString *downloadUrl = @"http://www.nasa.gov/sites/default/files/ladee_9.4.13_nasa_edge_0.jpg";
@interface CTViewController ()
@property (nonatomic, strong) NSOperation *downloadOperation;
@end
@implementation CTViewController
- (void)viewDidLoad
{
;
// Do any additional setup after loading the view, typically from a nib.
self.progressView.progress = 0;
self.downloadedImage.hidden = NO;
self.progressView.hidden = YES;
}
- (void)didReceiveMemoryWarning
{
;
// Dispose of any resources that can be recreated.
}
- (IBAction)downloadBackground:(id)sender {
// ;
;
}
- (IBAction)downloadImage:(id)sender {
;
}
- (void)downloadImageInBackground:(BOOL)background{
if (self.downloadOperation){
return;
}
CTSessionOperation *operation = ;
operation.downloadUrl = downloadUrl;
operation.progressAction = ^(double bytesWritten, double bytesExpected){
double progress = bytesWritten / bytesExpected;
dispatch_async(dispatch_get_main_queue(), ^{
self.progressView.progress = (float) progress;
});
};
operation.completionAction = ^(NSURL *imageUrl, BOOL success){
dispatch_async(dispatch_get_main_queue(), ^{
if (success){
UIImage *image = ];
self.downloadedImage.image = image;
NSLog(@"Done.......");
}
self.downloadedImage.hidden = NO;
self.progressView.progress = 0;
self.progressView.hidden = YES;
self.downloadOperation = nil;
});
};
operation.isBackground = background;
;
self.downloadedImage.hidden = YES;
self.progressView.hidden = NO;
self.downloadOperation = operation;
}
@end
</code></pre>
<h1>操作.h</h1>
<pre><code>#import <Foundation/Foundation.h>
typedef void (^CTProgressBlock)(double totalBytesWritten, double bytesExpected);
typedef void (^CTCompletionBlock)(NSURL *imageUrl, BOOL success);
@interface CTSessionOperation : NSOperation<NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDownloadDelegate>
@property (nonatomic) NSURLSessionDownloadTask *downloadTask;
@property (nonatomic) NSURLSession *session;
@property (nonatomic, strong) NSString *downloadUrl;
@property (strong) CTProgressBlock progressAction;
@property (strong) CTCompletionBlock completionAction;
@property (nonatomic, assign) BOOL isBackground;
- (void)enqueueOperation;
@end
</code></pre>
<h1>Operation.m</h1>
<pre><code>#import "CTSessionOperation.h"
#import "CTAppDelegate.h"
@implementation CTSessionOperation
- (NSOperationQueue *)operationQueue{
static NSOperationQueue *operationQueue = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
operationQueue = ;
;
});
return operationQueue;
}
- (NSURLSession *)session {
static NSURLSession *session = nil;
static NSURLSession *backgroundSession = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *configuration =;
session = ;
NSURLSessionConfiguration *backgroundConfiguration = [NSURLSessionConfiguration
backgroundSessionConfiguration:@"com.captech.NSURLSample.BackgroundSession"];
backgroundSession = [NSURLSession sessionWithConfiguration:backgroundConfiguration
delegate:self
delegateQueue:nil];
});
return self.isBackground ? backgroundSession : session;
}
- (void)enqueueOperation{
[ addOperation:self];
}
#pragma mark - NSOperation
- (void)start {
if (!self.isCancelled){
NSURL *downloadURL = ;
NSURLRequest *request = ;
self.downloadTask = ;
;
}
}
#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSFileManager *fileManager = ;
NSArray *urls = ;
NSURL *documentsDirectory = ;
NSURL *originalUrl = [ URL];
NSURL *destinationUrl = ];
NSError *error;
;
BOOL success = ;
if (self.completionAction){
self.completionAction(destinationUrl, success);
}
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
if (downloadTask == self.downloadTask && self.progressAction){
self.progressAction((double)totalBytesWritten, (double)totalBytesExpectedToWrite);
}
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {
}
#pragma mark - NSURLSessionTaskDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
if (self.progressAction){
self.progressAction((double)task.countOfBytesReceived, (double)task.countOfBytesExpectedToReceive);
}
self.downloadTask = nil;
}
#pragma mark - NSURLSessionDelegate
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
CTAppDelegate *appDelegate = (CTAppDelegate *)[ delegate];
if (appDelegate.backgroundSessionCompletionHandler) {
void (^completionHandler)() =appDelegate.backgroundSessionCompletionHandler;
appDelegate.backgroundSessionCompletionHandler = nil;
completionHandler();
}
}
@end
</code></pre>
<p>这是我的完整代码。请检查这个... :)</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>我会处理与您的下载方式略有不同的下载 :)</p>
<p>这是我的处理方式:)</p>
<p>1.声明一个NSOperation类并将下载文件的代码移动到这个类中</p>
<p>2.在您的 NSPertaion 类中声明一个协议(protocol),该协议(protocol)会将当前下载状态通知给确认此协议(protocol)的任何人</p>
<p>3.在您的第二个 VC 中启动 NSPertaion 并选择委托(delegate) :) 并相应地更新您的进度</p>
<ol start="4">
<li>在您的 secondVC 的 viewWillDisappear 中将其作为委托(delegate)删除,并将其作为委托(delegate)添加回 secondVC 的 ViewWillAppear 中的 NSOperation </li>
</ol>
<p>这里有一些相同的代码:)</p>
<p><em>下载Assets.h</em></p>
<pre><code>#import <Foundation/Foundation.h>
@protocol AssetDownloadStatusProtocol <NSObject>
-(void)updateStatusWithValue:(float) progress;
@end
@interface downloadAssets : NSOperation
@property (nonatomic,weak) id<AssetDownloadStatusProtocol> delegate;
@property (nonatomic,strong) NSString *urlToDownload;
-(id)initWithURL:(NSString *)url;
@end
</code></pre>
<p><em>下载Assets.m</em></p>
<pre><code> @implementation downloadChatAssets
-(id)initWithURL:(NSString *)url{
self=;
self.urlToDownload = url;
appdelegate=(AppDelegate *)[ delegate];
return self;
}
- (void)main {
// a lengthy operation
@autoreleasepool {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if (self.isCancelled) {
appdelegate.downloadingOperation = nil;
return;
}
else{
NSURLSessionConfiguration *configuration = ;
AFURLSessionManager *manager = ... //start downloading
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:URLRequest uploadProgress:nil downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
if (self.isCancelled) {
appdelegate.downloadingOperation = nil;
return;
}
self.progressAmount = downloadProgress.fractionCompleted;
dispatch_async(dispatch_get_main_queue(), ^{
;
});
} completionHandler:^(NSURLResponse * _Nonnull response, id_Nullable responseObject, NSError * _Nullable error) {
//handle completion here
}];
;
}
});
}
}
@end
</code></pre>
<p><em>AppDelegate.h</em></p>
<pre><code>@property (nonatomic, Strong) NSOperation *downloadingOperation;
</code></pre>
<p><em>SecondVC.h</em></p>
<pre><code>@interface SecondVC : UIViewController <AssetDownloadStatusProtocol>
</code></pre>
<p><em>SecondVC.m</em></p>
<pre><code>-(void)viewWillAppear:(BOOL)animated{
;
if(appdelegate.downloadingOperation) {
appdelegate.downloadingOperation.delegate = self;
}
}
-(void)viewWillDisappear:(BOOL)animated{
;
if(appdelegate.downloadingOperation) {
appdelegate.downloadingOperation.delegate = nil;
}
}
-(void)updateStatusWithValue:(float)progress{
dispatch_async(dispatch_get_main_queue(), ^{
//update your progress here
;
});
}
</code></pre>
<p>就是这样:) </p>
<p>随时开始下载操作:) </p>
<pre><code>appdelegate.downloadingOperation = yourDownloaderOperation;
;
</code></pre>
<p>你想阻止它说</p>
<pre><code>;
</code></pre>
<p>有多个下载操作??考虑使用 NSOperationQueue 或 Array 在 appdelegate 中保存 NSOperations :)</p>
<p><strong>编辑</strong></p>
<p>根据您在评论中的要求,您可以在您的 appDelegate 中保留对 CTOperation 的引用。</p>
<pre><code>@property (nonatomic, Strong) CTOperation *downloadingOperation;
</code></pre>
<p>你不需要声明协议(protocol),因为你已经声明了完成 block 和progressActionBlock :)</p>
<p>您所要做的就是检查您的 SecondVC viewWillAppear。</p>
<pre><code>-(void)viewWillAppear:(BOOL)animated{
;
if(appdelegate.downloadingOperation) {
appdelegate.downloadingOperation.progressAction = ^(double bytesWritten, double bytesExpected){
double progress = bytesWritten / bytesExpected;
dispatch_async(dispatch_get_main_queue(), ^{
self.progressView.progress = (float) progress;
});
};
appdelegate.downloadingOperation.completionAction = ^(NSURL *imageUrl, BOOL success){
dispatch_async(dispatch_get_main_queue(), ^{
if (success){
UIImage *image = ];
self.downloadedImage.image = image;
NSLog(@"Done.......");
}
self.downloadedImage.hidden = NO;
self.progressView.progress = 0;
self.progressView.hidden = YES;
self.downloadOperation = nil;
});
};
}
}
-(void)viewWillDisappear:(BOOL)animated{
;
if(appdelegate.downloadingOperation) {
appdelegate.downloadingOperation.progressAction = nil;
appdelegate.downloadingOperation.completionAction = nil;
}
}
</code></pre>
<p>并在您的 downloadImageInBackground 方法中而不是 <code>self.downloadOperation = operation;</code> 说 `appdelegate.downloadingOperation = operation;</p>
<p><strong>免责声明</strong> </p>
<p>请注意,此答案中提供的代码仅用于解释概念。请问我有句法或符号错误吗?请勿盲目复制粘贴。</p>
<p>简单吧???有疑问,请联系我 :) 快乐编码 :)</p></p>
<p style="font-size: 20px;">关于ios - 如何在 iOS 中以进度在后台下载多个 mp4 文件?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/36882179/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/36882179/
</a>
</p>
页:
[1]