// // JKNetworkSessionDelegate.m // Test Upload Progress // // Created by Jack on 2017/1/11. // Copyright © 2017年 mini1. All rights reserved. // #import "RANetworkTaskDelegate.h" #import "const.h" #import "RAUtils.h" @interface JLFileStream : NSObject @property (nonatomic,copy) NSString *filePath; @property (nonatomic,strong) NSInputStream *inputStream; @property (nonatomic,strong) NSOutputStream *outputStream; @end @implementation JLFileStream #pragma mark - life + (instancetype)jl_fileStreamOfPath:(NSString *)path { JLFileStream *stream = [[JLFileStream alloc] init]; stream.filePath = path; return stream; } - (void)setFilePath:(NSString *)filePath { _filePath = filePath; if (!filePath) { return; } if (_outputStream) { [_outputStream close]; } _outputStream = [NSOutputStream outputStreamToFileAtPath:self.filePath append:YES]; [_outputStream open]; } #pragma mark - out put stream - (void)jl_writeData:(NSData *)data { [self writeData:data toPath:self.filePath]; } - (void)writeData:(NSData *)data toPath:(NSString *)path { [self.outputStream write:data.bytes maxLength:data.length]; } - (void)jl_closeWriter { [self.outputStream close]; } @end @interface RANetworkTaskDelegate () @property (nonatomic,strong) NSMutableData *recvData; //@property (nonatomic,strong) NSMutableDictionary *result; @property (nonatomic,strong) JLFileStream *fileStream; @end @implementation RANetworkTaskDelegate + (instancetype)sharedInstance { RANetworkTaskDelegate *obj = nil; obj = [[RANetworkTaskDelegate alloc] init]; obj.recvData = [NSMutableData data]; // obj.result = [[JKNetworkResult alloc] init]; printf("new network delegate\n"); return obj; } #pragma mark - NSURLSessionTaskDelegate - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { double progress = (double)totalBytesSent / totalBytesExpectedToSend; if (self.p) { self.p(task,progress); } } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { // if (self.decryptHandler) { // // self.result.decryptHandler = self.decryptHandler; // // } // // if (error) { // // self.result.error = error; // // DebugLog(@"Delegate recv Error: %@",error.localizedDescription); // // } // // self.result.data = self.recvData; // // DebugLog(@"Delegate recv data %@",self.recvData); // // // if (self.isDownloadTask) { [self.fileStream jl_closeWriter]; if (error) { if (error.code != -999) { if (self.r) { NSMutableDictionary *resutlDic = [@{ @"result" : @0, @"msg" : error.localizedDescription } mutableCopy]; self.r(resutlDic); } } else { DebugLog(@"download task canceled"); } // 失败删除文件 BOOL isDir = NO; if ([[NSFileManager defaultManager] fileExistsAtPath:self.fileCachePath isDirectory:&isDir]) { if (!isDir) { [[NSFileManager defaultManager] removeItemAtPath:self.fileCachePath error:nil]; } } } else { if (self.r) { NSString *filePath = self.fileCachePath; if (!filePath) { filePath = @""; } NSMutableDictionary *resutlDic = [@{ @"result" : @2, @"path" : filePath, @"msg" : @"download complete" } mutableCopy]; self.r(resutlDic); } } } else { if (self.r) { if(self.recvData==nil) { self.r(nil); return; } NSMutableString *str = [[NSMutableString alloc] initWithData:self.recvData encoding:NSUTF8StringEncoding]; DebugLog(@"data string: %@",str); NSError *error1=nil; NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:self.recvData options:NSJSONReadingMutableLeaves error:&error1]; if(jsobj==nil)// 服务器返回不是json { jsobj=[NSMutableDictionary new]; [jsobj setValue:@"-30" forKey:@"result"]; [jsobj setValue:@"Can not upload to server, please contact administrator." forKey:@"msg"]; } dispatch_async(dispatch_get_main_queue(), ^{ self.r([jsobj mutableCopy]); }); } } printf("net work complete\n"); // [session invalidateAndCancel]; } #pragma mark - NSURLSessionDataDelegate - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{ if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){ if(/*[challenge.protectionSpace.host isEqualToString:@"96.75.188.41"]*/ true){ NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; completionHandler(NSURLSessionAuthChallengeUseCredential,credential); } } } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { DebugLog(@"Delegate recv response: %@",response); if (self.isDownloadTask) { // 文件保存地址 if (!self.fileCachePath) { self.fileCachePath = NSTemporaryDirectory(); } NSString *desPath = self.fileCachePath; NSError *err; BOOL isDir = NO; [[NSFileManager defaultManager] fileExistsAtPath:desPath isDirectory:&isDir]; if (isDir) { if (response.suggestedFilename) { desPath = [self.fileCachePath stringByAppendingPathComponent:response.suggestedFilename]; } else { desPath = [self.fileCachePath stringByAppendingPathComponent:[NSUUID UUID].UUIDString]; } } // 如果文件存在 if ([[NSFileManager defaultManager] fileExistsAtPath:desPath]) { [[NSFileManager defaultManager] removeItemAtPath:desPath error:&err]; if (err) { completionHandler(NSURLSessionResponseCancel); return; } } self.fileCachePath = desPath; self.fileStream = [JLFileStream jl_fileStreamOfPath:self.fileCachePath]; } // self.result.response = response; completionHandler(NSURLSessionResponseAllow); } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { if (!self.isDownloadTask) { [self.recvData appendData:data]; } else { if (self.p) { int64_t totalExpectedRevc = [dataTask countOfBytesExpectedToReceive]; int64_t totalRevc = [dataTask countOfBytesReceived]; double progress = (double)totalRevc / totalExpectedRevc; self.p(dataTask,progress); } [self.fileStream jl_writeData:data]; } } @end