Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // BackgroundSessionManager.h
- #import <AFNetworking/AFNetworking.h>
- #import "AFHTTPSessionManager.h"
- @interface BackgroundSessionManager : AFURLSessionManager
- + (instancetype)sharedManager;
- @property (nonatomic, copy) void (^savedCompletionHandler)(void);
- + (AFURLSessionManager *)uploadWithIdentifier:(NSString *)indetifier
- request:(NSURLRequest *)request
- progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
- completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
- @end
- // BackgroundSessionManager.m
- #import "BackgroundSessionManager.h"
- static NSString * const kBackgroundSessionIdentifier = @"com.pickMyHeart.backgroundsession";
- static NSMutableDictionary *dicUploadingTask;
- @implementation BackgroundSessionManager
- + (AFURLSessionManager *)uploadWithIdentifier:(NSString *)indetifier
- request:(NSURLRequest *)request
- progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
- completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
- {
- static id dicUploadingTask = nil;
- static dispatch_once_t onceToken;
- dispatch_once(&onceToken, ^{
- dicUploadingTask = [[NSMutableDictionary alloc] init];
- });
- AFURLSessionManager *manager = [dicUploadingTask objectForKey:indetifier];
- if(!manager)
- {
- manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:indetifier]];
- [dicUploadingTask setObject:manager forKey:indetifier];
- NSURLSessionUploadTask *uploadTask = [manager
- uploadTaskWithStreamedRequest:request
- progress:^(NSProgress * _Nonnull uploadProgress) {
- uploadProgressBlock(uploadProgress);
- }
- completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
- completionHandler(response,responseObject,error);
- }];
- [uploadTask resume];
- }
- return manager;
- }
- + (instancetype)sharedManager
- {
- static id sharedMyManager = nil;
- static dispatch_once_t onceToken;
- dispatch_once(&onceToken, ^{
- sharedMyManager = [[self alloc] init];
- });
- return sharedMyManager;
- }
- - (instancetype)init
- {
- NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:kBackgroundSessionIdentifier];
- self = [super initWithSessionConfiguration:configuration];
- if (self) {
- [self configureDownloadFinished]; // when download done, save file
- [self configureBackgroundSessionFinished]; // when entire background session done, call completion handler
- //[self configureAuthentication]; // my server uses authentication, so let's handle that; if you don't use authentication challenges, you can remove this
- }
- return self;
- }
- - (void)configureDownloadFinished
- {
- // just save the downloaded file to documents folder using filename from URL
- [self setDownloadTaskDidFinishDownloadingBlock:^NSURL *(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location) {
- if ([downloadTask.response isKindOfClass:[NSHTTPURLResponse class]]) {
- NSInteger statusCode = [(NSHTTPURLResponse *)downloadTask.response statusCode];
- if (statusCode != 200) {
- // handle error here, e.g.
- NSLog(@"%@ failed (statusCode = %ld)", [downloadTask.originalRequest.URL lastPathComponent], statusCode);
- return nil;
- }
- }
- NSString *filename = [downloadTask.originalRequest.URL lastPathComponent];
- NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
- NSString *path = [documentsPath stringByAppendingPathComponent:filename];
- return [NSURL fileURLWithPath:path];
- }];
- [self setTaskDidCompleteBlock:^(NSURLSession *session, NSURLSessionTask *task, NSError *error) {
- if (error) {
- // handle error here, e.g.,
- NSLog(@"%@: %@", [task.originalRequest.URL lastPathComponent], error);
- }
- }];
- }
- - (void)configureBackgroundSessionFinished
- {
- typeof(self) __weak weakSelf = self;
- [self setDidFinishEventsForBackgroundURLSessionBlock:^(NSURLSession *session) {
- if (weakSelf.savedCompletionHandler) {
- weakSelf.savedCompletionHandler();
- weakSelf.savedCompletionHandler = nil;
- }
- }];
- }
- - (void)configureAuthentication
- {
- NSURLCredential *myCredential = [NSURLCredential credentialWithUser:@"userid" password:@"password" persistence:NSURLCredentialPersistenceForSession];
- [self setTaskDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential) {
- if (challenge.previousFailureCount == 0) {
- *credential = myCredential;
- return NSURLSessionAuthChallengeUseCredential;
- } else {
- return NSURLSessionAuthChallengePerformDefaultHandling;
- }
- }];
- }
- @end
Add Comment
Please, Sign In to add comment