菜鸟教程小白 发表于 2022-12-13 11:53:44

ios - NSURLSession 方法不调用


                                            <p><p>我想通过使用 NSURLSession 而不是 NSURLConnection 从服务器下载文件。但是当我使用它时,一些委托(delegate)方法没有调用,我不知道为什么。</p>

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

@interface ViewController ()&lt;NSURLSessionDelegate,NSURLSessionDataDelegate,NSURLSessionDownloadDelegate&gt;

@property (strong,nonatomic) NSURLSessionDownloadTask *downloadTask;
@property (strong,nonatomic) NSURLSession *session;


@end

@implementation ViewController


-(void)viewWillAppear:(BOOL)animated{
;
NSURLSessionConfiguration *backgroundConfiguration = ;
self.session = ;
}

- (void)viewDidLoad {
;
// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
;
// Dispose of any resources that can be recreated.
}
- (IBAction)startDownload:(id)sender {
NSURL *downloadRUL = ;
self.downloadTask = ;
;
}

- (IBAction)stopDownload:(id)sender {

}

// ====== THIS METHOD IS NOT CALLING

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{

if (totalBytesExpectedToWrite == NSURLSessionTransferSizeUnknown) {
    return;
} else {
    [ addOperationWithBlock:^{
      double progress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
      NSLog(@&#34;Downloading progress : %f&#34;,progress);
    }];
}

}

// ==============

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {

if (error != nil) {
    NSLog(@&#34;Error : %@&#34;,);
} else {
    NSLog(@&#34;Download finished&#34;);
}

}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{

NSError *error;
NSFileManager *fileManager = ;

NSArray *urls = ;
NSURL *documentsDirectory = ;
NSURL *originalURL = [ URL];
NSURL *destinationURL = ];
;
BOOL success = ;

if (success) {
    NSLog(@&#34;Download finished&#34;);
} else {
    NSLog(@&#34;Error : %@&#34;,error.description);
}

}

@end
</code></pre>

<p>我跟进了许多教程,但仍然无法正常工作。请帮我解决这个问题。谢谢!</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><pre><code> #import &#34;ViewController.h&#34;

@interface ViewController ()&lt;NSURLSessionDelegate, NSURLSessionTaskDelegate&gt;

@property (nonatomic, strong) NSMutableData *activeDownload;
@property (nonatomic, strong) NSURLSessionTask *downloadTask;
@property (nonatomic, assign) NSInteger downloadSize;
@property (nonatomic, assign) NSInteger downloadedSize;


@end

@implementation ViewController

- (void)viewDidLoad {
    ;
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    ;
    // Dispose of any resources that can be recreated.
}
- (IBAction)startDownload:(id)sender {
    self.downloadedSize = 0;
    NSURL *nsurl = ;
    NSURLSessionConfiguration *config = ;
    NSURLSession *downloadSession = ;
    NSMutableURLRequest *request = [ initWithURL:nsurl];
    self.downloadTask = ;
    ;
    ;
}

- (IBAction)stopDownload:(id)sender {
    ;
    self.downloadTask = nil;
    self.activeDownload = nil;
}

#pragma mark - NSURLSessionDataDelegate methods

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    completionHandler(NSURLSessionResponseAllow);
    self.activeDownload = [ init];
    NSString *contentLength = [[(NSHTTPURLResponse *)response allHeaderFields] valueForKey:@&#34;Content-Length&#34;];
    self.downloadSize = contentLength.integerValue;
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    ;
    self.downloadedSize += ;
    float downloadProgress = ((float) self.downloadedSize / (float) self.downloadSize) * 100;
    //percentage of downloading progress
}

#pragma mark - NSURLSessionTaskDelegate methods

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if (error != nil) {
      NSLog(@&#34;Error : %@&#34;,);
    } else {
      NSLog(@&#34;Download finished&#34;);
      //the data is in self.activeDownload
    }
    self.activeDownload = nil;
    self.downloadTask = nil;
}

@end
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - NSURLSession 方法不调用,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/33888475/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/33888475/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - NSURLSession 方法不调用