菜鸟教程小白 发表于 2022-12-13 00:43:58

ios - 使用 NSURLSession 下载多个文件


                                            <p><p><strong>我想从服务器的url数组中一个一个下载多个文件。</strong></p>

<p>我需要显示每个下载文件的进度,用户也可以取消它。</p>

<p><strong>ViewControllerh:</strong></p>

<pre><code>#import &lt;UIKit/UIKit.h&gt;

@interface ViewController : UIViewController {
    IBOutlet UIView *vw_download;
    IBOutlet UILabel *lbl_BookTitle;
    IBOutlet UILabel *lbl_BookDes;
    IBOutlet UILabel *lbl_downloadStatus;
    IBOutlet UIImageView *img_todownload;
    IBOutlet UIProgressView *vw_downloadbar;
    IBOutlet UIButton *btn_stopDownload;
}

-(IBAction)btn_stopDownloading:(id)sender;

@end
</code></pre>

<p><strong>ViewController.m:</strong></p>

<pre><code>#import &#34;ViewController.h&#34;

@interface ViewController ()&lt;NSURLSessionDelegate&gt; {
    NSMutableArray *downloadLinksArray;
    NSURLSession *session ;
    NSURLSessionDownloadTask *task;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    downloadLinksArray=[initWithObjects:@&#34;URL1&#34;,@&#34;URL2&#34;, @&#34;URL3&#34;, @&#34;URL4&#34;,nil];

    ;
    lbl_downloadStatus.text=;
    ;
    // Do any additional setup after loading the view, typically from a nib.
}

-(IBAction)startDownload:(id)sender {
    //;

    for (int i=0;i&lt; ;i++) {
      NSURL *Url= ]];

      NSURLSessionConfiguration *configuration = ;

      session = ];

      NSURLRequest* request = ;

      task = ;

      ;
    }
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    CGFloat percentDone = (double)totalBytesWritten/(double)totalBytesExpectedToWrite;
    // Notify user.

    waitUntilDone:NO];
}

- (void) updateProgress:(NSNumber *)percent {
    ;
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    // Either move the data from the location to a permanent location, or do something with the data at that location.
}

-(IBAction)btn_stopDownloading:(id)sender {
    ;
    ;
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>如果你想下载多个文件并且当它完成你想通知:</p>

<p><strong>请检查代码 - 使用 NSFileManager :</strong></p>

<pre><code>NSURLSessionConfiguration *configuration = ;
NSURLSession            *session       = ;

NSString      *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSFileManager *fileManager   = ;

for (NSString *filename in self.filenames)
{
    NSURL *url = ;
    NSURLSessionTask *downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

      NSString *finalPath = ;

      BOOL success;
      NSError *fileManagerError;
      if () {
            success = ;
            NSAssert(success, @&#34;removeItemAtPath error: %@&#34;, fileManagerError);
      }

      success = error:&amp;fileManagerError];
      NSAssert(success, @&#34;moveItemAtURL error: %@&#34;, fileManagerError);

      NSLog(@&#34;finished %@&#34;, filename);
    }];
    ;
}
</code></pre>

<p><strong>你可以选择:NSOperationQueue</strong></p>

<pre><code>NSOperationQueue *queue = [ init];
queue.maxConcurrentOperationCount = 4;

NSBlockOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
    [ addOperationWithBlock:^{
      ;
    }];
}];

for (NSURL* url in urlArray)
{
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
      NSData *data = ;
      NSString *filename = ];
      ;
    }];
    ;
}

;
;
</code></pre>

<p><strong>它将显示下载文件的百分比:</strong></p>

<p>您可以根据您的要求进行更改:(我没有测试过,但它会起作用)。</p>

<pre><code>@property (nonatomic, retain) NSMutableData *dataToDownload;
@property (nonatomic) float downloadSize;

- (void)viewDidLoad {
    ;

    NSURLSessionConfiguration *defaultConfigObject = ;

    NSURLSession *defaultSession = ];

    NSURL *url = ;
    NSURLSessionDataTask *dataTask = ;

    ;
}

- (void)didReceiveMemoryWarning {
    ;
    // Dispose of any resources that can be recreated.
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    completionHandler(NSURLSessionResponseAllow);

    progressBar.progress=0.0f;
    _downloadSize=;
    _dataToDownload=[init];
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    ;
    progressBar.progress=[ _dataToDownload length ]/_downloadSize;
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 使用 NSURLSession 下载多个文件,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/43245369/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/43245369/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 使用 NSURLSession 下载多个文件