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