• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - NSURLSession 方法不调用

[复制链接]
菜鸟教程小白 发表于 2022-12-13 11:53:44 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

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

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDelegate,NSURLSessionDataDelegate,NSURLSessionDownloadDelegate>

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


@end

@implementation ViewController


-(void)viewWillAppearBOOL)animated{
[super viewWillAppear:animated];
NSURLSessionConfiguration *backgroundConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier"com.webcash.TestingNSURLSession"];
self.session = [NSURLSession sessionWithConfiguration:backgroundConfiguration delegate:self delegateQueue:nil];
}

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

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)startDownloadid)sender {
NSURL *downloadRUL = [NSURL URLWithString"http://laguboard.com/music/down/33867378/2794942/NTU0NktpZE56eERWZGxVeC9zTS9LVUd1TEhkZTE0cFZuaW1QS1pFMHVhOUNkM2ZoZEE=/(http://mp3xload.wapka.me).mp3"];
self.downloadTask = [self.session downloadTaskWithURL:downloadRUL];
[self.downloadTask resume];
}

- (IBAction)stopDownloadid)sender {

}

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

 -(void)URLSessionNSURLSession *)session downloadTaskNSURLSessionDownloadTask *)downloadTask didWriteDataint64_t)bytesWritten totalBytesWrittenint64_t)totalBytesWritten totalBytesExpectedToWriteint64_t)totalBytesExpectedToWrite{

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

}

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

-(void)URLSessionNSURLSession *)session taskNSURLSessionTask *)task didCompleteWithError:(NSError *)error {

if (error != nil) {
    NSLog(@"Error : %@",[error localizedDescription]);
} else {
    NSLog(@"Download finished");
}

}

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

NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];

NSArray *urls = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *documentsDirectory = [urls objectAtIndex:0];
NSURL *originalURL = [[downloadTask originalRequest] URL];
NSURL *destinationURL = [documentsDirectory URLByAppendingPathComponent:[originalURL lastPathComponent]];
[fileManager removeItemAtURL:destinationURL error:NULL];
BOOL success = [fileManager copyItemAtURL:location toURL:destinationURL error:&error];

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

}

@end

我跟进了许多教程,但仍然无法正常工作。请帮我解决这个问题。谢谢!



Best Answer-推荐答案


 #import "ViewController.h"

@interface ViewController ()<NSURLSessionDelegate, NSURLSessionTaskDelegate>

@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 {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)startDownload:(id)sender {
    self.downloadedSize = 0;
    NSURL *nsurl = [NSURL URLWithString"http://laguboard.com/music/down/33867378/2794942/NTU0NktpZE56eERWZGxVeC9zTS9LVUd1TEhkZTE0cFZuaW1QS1pFMHVhOUNkM2ZoZEE=/(http://mp3xload.wapka.me).mp3"];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *downloadSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:nsurl];
    self.downloadTask = [downloadSession dataTaskWithRequest:request];
    [self.downloadTask resume];
    [downloadSession finishTasksAndInvalidate];
}

- (IBAction)stopDownload:(id)sender {
    [self.downloadTask cancel];
    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 = [[NSMutableData alloc] init];
    NSString *contentLength = [[(NSHTTPURLResponse *)response allHeaderFields] valueForKey"Content-Length"];
    self.downloadSize = contentLength.integerValue;
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [self.activeDownload appendData:data];
    self.downloadedSize += [data length];
    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(@"Error : %@",[error localizedDescription]);
    } else {
        NSLog(@"Download finished");
        //the data is in self.activeDownload
    }
    self.activeDownload = nil;
    self.downloadTask = nil;
}

@end

关于ios - NSURLSession 方法不调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33888475/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap