RANetworkTaskDelegate.m 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. //
  2. // JKNetworkSessionDelegate.m
  3. // Test Upload Progress
  4. //
  5. // Created by Jack on 2017/1/11.
  6. // Copyright © 2017年 mini1. All rights reserved.
  7. //
  8. #import "RANetworkTaskDelegate.h"
  9. #import "const.h"
  10. #import "RAUtils.h"
  11. @interface JLFileStream : NSObject
  12. @property (nonatomic,copy) NSString *filePath;
  13. @property (nonatomic,strong) NSInputStream *inputStream;
  14. @property (nonatomic,strong) NSOutputStream *outputStream;
  15. @end
  16. @implementation JLFileStream
  17. #pragma mark - life
  18. + (instancetype)jl_fileStreamOfPath:(NSString *)path {
  19. JLFileStream *stream = [[JLFileStream alloc] init];
  20. stream.filePath = path;
  21. return stream;
  22. }
  23. - (void)setFilePath:(NSString *)filePath {
  24. _filePath = filePath;
  25. if (!filePath) {
  26. return;
  27. }
  28. if (_outputStream) {
  29. [_outputStream close];
  30. }
  31. _outputStream = [NSOutputStream outputStreamToFileAtPath:self.filePath append:YES];
  32. [_outputStream open];
  33. }
  34. #pragma mark - out put stream
  35. - (void)jl_writeData:(NSData *)data {
  36. [self writeData:data toPath:self.filePath];
  37. }
  38. - (void)writeData:(NSData *)data toPath:(NSString *)path {
  39. [self.outputStream write:data.bytes maxLength:data.length];
  40. }
  41. - (void)jl_closeWriter {
  42. [self.outputStream close];
  43. }
  44. @end
  45. @interface RANetworkTaskDelegate ()
  46. @property (nonatomic,strong) NSMutableData *recvData;
  47. //@property (nonatomic,strong) NSMutableDictionary *result;
  48. @property (nonatomic,strong) JLFileStream *fileStream;
  49. @end
  50. @implementation RANetworkTaskDelegate
  51. + (instancetype)sharedInstance {
  52. RANetworkTaskDelegate *obj = nil;
  53. obj = [[RANetworkTaskDelegate alloc] init];
  54. obj.recvData = [NSMutableData data];
  55. // obj.result = [[JKNetworkResult alloc] init];
  56. printf("new network delegate\n");
  57. return obj;
  58. }
  59. #pragma mark - NSURLSessionTaskDelegate
  60. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
  61. double progress = (double)totalBytesSent / totalBytesExpectedToSend;
  62. if (self.p) {
  63. self.p(task,progress);
  64. }
  65. }
  66. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
  67. // if (self.decryptHandler) {
  68. //
  69. // self.result.decryptHandler = self.decryptHandler;
  70. //
  71. // }
  72. //
  73. // if (error) {
  74. //
  75. // self.result.error = error;
  76. //
  77. // DebugLog(@"Delegate recv Error: %@",error.localizedDescription);
  78. //
  79. // }
  80. //
  81. // self.result.data = self.recvData;
  82. //
  83. // DebugLog(@"Delegate recv data %@",self.recvData);
  84. //
  85. //
  86. //
  87. if (self.isDownloadTask) {
  88. [self.fileStream jl_closeWriter];
  89. if (error) {
  90. if (error.code != -999) {
  91. if (self.r) {
  92. NSMutableDictionary *resutlDic = [@{
  93. @"result" : @0,
  94. @"msg" : error.localizedDescription
  95. } mutableCopy];
  96. self.r(resutlDic);
  97. }
  98. } else {
  99. DebugLog(@"download task canceled");
  100. }
  101. // 失败删除文件
  102. BOOL isDir = NO;
  103. if ([[NSFileManager defaultManager] fileExistsAtPath:self.fileCachePath isDirectory:&isDir]) {
  104. if (!isDir) {
  105. [[NSFileManager defaultManager] removeItemAtPath:self.fileCachePath error:nil];
  106. }
  107. }
  108. } else {
  109. if (self.r) {
  110. NSString *filePath = self.fileCachePath;
  111. if (!filePath) {
  112. filePath = @"";
  113. }
  114. NSMutableDictionary *resutlDic = [@{
  115. @"result" : @2,
  116. @"path" : filePath,
  117. @"msg" : @"download complete"
  118. } mutableCopy];
  119. self.r(resutlDic);
  120. }
  121. }
  122. } else {
  123. if (self.r) {
  124. if(self.recvData==nil)
  125. {
  126. self.r(nil);
  127. return;
  128. }
  129. NSMutableString *str = [[NSMutableString alloc] initWithData:self.recvData encoding:NSUTF8StringEncoding];
  130. DebugLog(@"data string: %@",str);
  131. NSError *error1=nil;
  132. NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:self.recvData options:NSJSONReadingMutableLeaves error:&error1];
  133. if(jsobj==nil)// 服务器返回不是json
  134. {
  135. jsobj=[NSMutableDictionary new];
  136. [jsobj setValue:@"-30" forKey:@"result"];
  137. [jsobj setValue:@"Can not upload to server, please contact administrator." forKey:@"msg"];
  138. }
  139. dispatch_async(dispatch_get_main_queue(), ^{
  140. self.r([jsobj mutableCopy]);
  141. });
  142. }
  143. }
  144. printf("net work complete\n");
  145. //
  146. [session invalidateAndCancel];
  147. }
  148. #pragma mark - NSURLSessionDataDelegate
  149. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{
  150. if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
  151. if(/*[challenge.protectionSpace.host isEqualToString:@"96.75.188.41"]*/ true){
  152. NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  153. completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
  154. }
  155. }
  156. }
  157. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
  158. DebugLog(@"Delegate recv response: %@",response);
  159. if (self.isDownloadTask) {
  160. // 文件保存地址
  161. if (!self.fileCachePath) {
  162. self.fileCachePath = NSTemporaryDirectory();
  163. }
  164. NSString *desPath = self.fileCachePath;
  165. NSError *err;
  166. BOOL isDir = NO;
  167. [[NSFileManager defaultManager] fileExistsAtPath:desPath isDirectory:&isDir];
  168. if (isDir) {
  169. if (response.suggestedFilename) {
  170. desPath = [self.fileCachePath stringByAppendingPathComponent:response.suggestedFilename];
  171. } else {
  172. desPath = [self.fileCachePath stringByAppendingPathComponent:[NSUUID UUID].UUIDString];
  173. }
  174. }
  175. // 如果文件存在
  176. if ([[NSFileManager defaultManager] fileExistsAtPath:desPath]) {
  177. [[NSFileManager defaultManager] removeItemAtPath:desPath error:&err];
  178. if (err) {
  179. completionHandler(NSURLSessionResponseCancel);
  180. return;
  181. }
  182. }
  183. self.fileCachePath = desPath;
  184. self.fileStream = [JLFileStream jl_fileStreamOfPath:self.fileCachePath];
  185. }
  186. // self.result.response = response;
  187. completionHandler(NSURLSessionResponseAllow);
  188. }
  189. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
  190. if (!self.isDownloadTask) {
  191. [self.recvData appendData:data];
  192. } else {
  193. if (self.p) {
  194. int64_t totalExpectedRevc = [dataTask countOfBytesExpectedToReceive];
  195. int64_t totalRevc = [dataTask countOfBytesReceived];
  196. double progress = (double)totalRevc / totalExpectedRevc;
  197. self.p(dataTask,progress);
  198. }
  199. [self.fileStream jl_writeData:data];
  200. }
  201. }
  202. @end