关键代码:使用后台下载PDF文件
- (void)startDownloadPDF{ NSURLSession *session = [self session]; NSString *downloadURLString = _fileURL; NSURL *downloadURL = [NSURL URLWithString:[kGlobal getEncodeUrl:downloadURLString]];
//使用NSMutableURLRequest进行AD认证 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:downloadURL]; NSString *authString = [[[NSString stringWithFormat:@"%@:%@", kGlobal.userInfo.sAccount, kGlobal.userInfo.sPassword] dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString]; authString = [NSString stringWithFormat: @"Basic %@", authString]; [req setValue:authString forHTTPHeaderField:@"Authorization"]; NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:req]; //执行resume 保证开始了任务 [task resume]; } //后台会话(保证只有一个后台会话) -(NSURLSession *)session { static NSURLSession *session; static dispatch_once_t token; dispatch_once(&token, ^{ //后台下载 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"rich"]; configuration.discretionary = YES; //使用配置的NSURLSessionConfiguration获取NSSession,并且设置委托 session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; }); return session; }
//HTTPS认证 - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{ NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; __block NSURLCredential *credential = nil; if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; if (credential) { disposition = NSURLSessionAuthChallengeUseCredential; } else { disposition = NSURLSessionAuthChallengePerformDefaultHandling; } } else { disposition = NSURLSessionAuthChallengePerformDefaultHandling; } if (completionHandler) { completionHandler(disposition, credential); } }
//打印下载过程,下载的百分比 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { float percent = (float)totalBytesWritten/totalBytesExpectedToWrite; NSLog(@"%f",percent); }
//下载完成之后的文件存储在临时目录中,下载完成之后,转移文件的目录 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { // NSString *dirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; // NSString *path = [dirPath stringByAppendingPathComponent:@"1.mp3"]; // // NSFileManager *manager = [NSFileManager defaultManager]; // if ([manager fileExistsAtPath:path isDirectory:NO]) { // [manager removeItemAtPath:path error:nil]; // } // // [manager moveItemAtPath:[location path] toPath:path error:nil]; } //任务结束 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"%s:%@",__func__,error); if (error == NULL) { self.rightButton.enabled = YES; } }