RANetworkTaskDelegate.m 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. NSMutableDictionary *resutlDic = [@{
  109. @"result" : @2,
  110. @"path" : self.fileCachePath,
  111. @"msg" : @"download complete"
  112. } mutableCopy];
  113. self.r(resutlDic);
  114. }
  115. }
  116. } else {
  117. if (self.r) {
  118. if(self.recvData==nil)
  119. {
  120. self.r(nil);
  121. return;
  122. }
  123. NSMutableString *str = [[NSMutableString alloc] initWithData:self.recvData encoding:NSUTF8StringEncoding];
  124. NSLog(@"data string: %@",str);
  125. NSError *error1=nil;
  126. NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:self.recvData options:NSJSONReadingMutableLeaves error:&error1];
  127. if(jsobj==nil)// 服务器返回不是json
  128. {
  129. jsobj=[NSMutableDictionary new];
  130. [jsobj setValue:@"-30" forKey:@"result"];
  131. [jsobj setValue:@"Can not upload to server, please contact administrator." forKey:@"msg"];
  132. }
  133. self.r([jsobj mutableCopy]);
  134. }
  135. }
  136. printf("net work complete\n");
  137. //
  138. [session invalidateAndCancel];
  139. }
  140. #pragma mark - NSURLSessionDataDelegate
  141. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{
  142. if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
  143. if(/*[challenge.protectionSpace.host isEqualToString:@"96.75.188.41"]*/ true){
  144. NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  145. completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
  146. }
  147. }
  148. }
  149. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
  150. NSLog(@"Delegate recv response: %@",response);
  151. if (self.isDownloadTask) {
  152. // 文件保存地址
  153. if (!self.fileCachePath) {
  154. self.fileCachePath = NSTemporaryDirectory();
  155. }
  156. NSString *desPath = self.fileCachePath;
  157. NSError *err;
  158. BOOL isDir = NO;
  159. [[NSFileManager defaultManager] fileExistsAtPath:desPath isDirectory:&isDir];
  160. if (isDir) {
  161. if (response.suggestedFilename) {
  162. desPath = [self.fileCachePath stringByAppendingPathComponent:response.suggestedFilename];
  163. } else {
  164. desPath = [self.fileCachePath stringByAppendingPathComponent:[NSUUID UUID].UUIDString];
  165. }
  166. }
  167. // 如果文件存在
  168. if ([[NSFileManager defaultManager] fileExistsAtPath:desPath]) {
  169. [[NSFileManager defaultManager] removeItemAtPath:desPath error:&err];
  170. if (err) {
  171. completionHandler(NSURLSessionResponseCancel);
  172. return;
  173. }
  174. }
  175. self.fileCachePath = desPath;
  176. self.fileStream = [JLFileStream jl_fileStreamOfPath:self.fileCachePath];
  177. }
  178. // self.result.response = response;
  179. completionHandler(NSURLSessionResponseAllow);
  180. }
  181. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
  182. if (!self.isDownloadTask) {
  183. [self.recvData appendData:data];
  184. } else {
  185. if (self.p) {
  186. int64_t totalExpectedRevc = [dataTask countOfBytesExpectedToReceive];
  187. int64_t totalRevc = [dataTask countOfBytesReceived];
  188. double progress = (double)totalRevc / totalExpectedRevc;
  189. self.p(dataTask,progress);
  190. }
  191. [self.fileStream jl_writeData:data];
  192. }
  193. }
  194. @end