Advertisement
Guest User

Untitled

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