RANetworkTaskDelegate.m 8.1 KB

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