Samouker

Untitled

Aug 5th, 2016
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.69 KB | None | 0 0
  1.  
  2. // BackgroundSessionManager.h
  3.  
  4. #import <AFNetworking/AFNetworking.h>
  5. #import "AFHTTPSessionManager.h"
  6.  
  7. @interface BackgroundSessionManager : AFURLSessionManager
  8.  
  9. + (instancetype)sharedManager;
  10.  
  11. @property (nonatomic, copy) void (^savedCompletionHandler)(void);
  12.  
  13. + (AFURLSessionManager *)uploadWithIdentifier:(NSString *)indetifier
  14. request:(NSURLRequest *)request
  15. progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
  16. completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
  17.  
  18.  
  19. @end
  20.  
  21.  
  22.  
  23. // BackgroundSessionManager.m
  24. #import "BackgroundSessionManager.h"
  25.  
  26. static NSString * const kBackgroundSessionIdentifier = @"com.pickMyHeart.backgroundsession";
  27. static NSMutableDictionary *dicUploadingTask;
  28.  
  29. @implementation BackgroundSessionManager
  30.  
  31.  
  32. + (AFURLSessionManager *)uploadWithIdentifier:(NSString *)indetifier
  33. request:(NSURLRequest *)request
  34. progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
  35. completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
  36. {
  37.  
  38. static id dicUploadingTask = nil;
  39. static dispatch_once_t onceToken;
  40. dispatch_once(&onceToken, ^{
  41. dicUploadingTask = [[NSMutableDictionary alloc] init];
  42. });
  43.  
  44. AFURLSessionManager *manager = [dicUploadingTask objectForKey:indetifier];
  45.  
  46. if(!manager)
  47. {
  48. manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:indetifier]];
  49. [dicUploadingTask setObject:manager forKey:indetifier];
  50.  
  51. NSURLSessionUploadTask *uploadTask = [manager
  52. uploadTaskWithStreamedRequest:request
  53. progress:^(NSProgress * _Nonnull uploadProgress) {
  54.  
  55. uploadProgressBlock(uploadProgress);
  56. }
  57. completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
  58. completionHandler(response,responseObject,error);
  59. }];
  60.  
  61. [uploadTask resume];
  62. }
  63.  
  64. return manager;
  65. }
  66.  
  67. + (instancetype)sharedManager
  68. {
  69. static id sharedMyManager = nil;
  70. static dispatch_once_t onceToken;
  71. dispatch_once(&onceToken, ^{
  72. sharedMyManager = [[self alloc] init];
  73. });
  74. return sharedMyManager;
  75. }
  76.  
  77.  
  78. - (instancetype)init
  79. {
  80. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:kBackgroundSessionIdentifier];
  81. self = [super initWithSessionConfiguration:configuration];
  82. if (self) {
  83. [self configureDownloadFinished]; // when download done, save file
  84. [self configureBackgroundSessionFinished]; // when entire background session done, call completion handler
  85. //[self configureAuthentication]; // my server uses authentication, so let's handle that; if you don't use authentication challenges, you can remove this
  86. }
  87. return self;
  88. }
  89.  
  90. - (void)configureDownloadFinished
  91. {
  92. // just save the downloaded file to documents folder using filename from URL
  93.  
  94. [self setDownloadTaskDidFinishDownloadingBlock:^NSURL *(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location) {
  95. if ([downloadTask.response isKindOfClass:[NSHTTPURLResponse class]]) {
  96. NSInteger statusCode = [(NSHTTPURLResponse *)downloadTask.response statusCode];
  97. if (statusCode != 200) {
  98. // handle error here, e.g.
  99.  
  100. NSLog(@"%@ failed (statusCode = %ld)", [downloadTask.originalRequest.URL lastPathComponent], statusCode);
  101. return nil;
  102. }
  103. }
  104.  
  105. NSString *filename = [downloadTask.originalRequest.URL lastPathComponent];
  106. NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
  107. NSString *path = [documentsPath stringByAppendingPathComponent:filename];
  108. return [NSURL fileURLWithPath:path];
  109. }];
  110.  
  111. [self setTaskDidCompleteBlock:^(NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  112. if (error) {
  113. // handle error here, e.g.,
  114.  
  115. NSLog(@"%@: %@", [task.originalRequest.URL lastPathComponent], error);
  116. }
  117. }];
  118. }
  119.  
  120. - (void)configureBackgroundSessionFinished
  121. {
  122. typeof(self) __weak weakSelf = self;
  123.  
  124. [self setDidFinishEventsForBackgroundURLSessionBlock:^(NSURLSession *session) {
  125. if (weakSelf.savedCompletionHandler) {
  126. weakSelf.savedCompletionHandler();
  127. weakSelf.savedCompletionHandler = nil;
  128. }
  129. }];
  130. }
  131.  
  132. - (void)configureAuthentication
  133. {
  134. NSURLCredential *myCredential = [NSURLCredential credentialWithUser:@"userid" password:@"password" persistence:NSURLCredentialPersistenceForSession];
  135.  
  136. [self setTaskDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential) {
  137. if (challenge.previousFailureCount == 0) {
  138. *credential = myCredential;
  139. return NSURLSessionAuthChallengeUseCredential;
  140. } else {
  141. return NSURLSessionAuthChallengePerformDefaultHandling;
  142. }
  143. }];
  144. }
  145.  
  146.  
  147. @end
Add Comment
Please, Sign In to add comment