Делегаты NSURLSession разделены по классам — NSURLSession, NSURLUploadTask, NSURLDownloadTask

Я нахожусь в процессе создания функции загрузки/выгрузки мультимедиа для своего приложения. У меня нормально работала очередь для загрузки, но когда я добавлял загрузки и необходимые делегаты загрузки, делегат загрузки назывался событием, хотя задача заключалась в загрузке. Моя первоначальная структура класса представляла собой одноэлементный QueueController, который имел NSURLSession и делегаты (но не загрузку), а также TransferModel, который мог содержать либо загрузку, либо загрузку. Когда я пытался добавить загрузки, обратные вызовы не работали должным образом, поэтому я решил поместить делегатов, связанных с передачей, в два подкласса TransferUploadModel и TransferDownloadModel, но теперь мои делегаты не срабатывают.

Вот как выглядят сигнатуры моих методов: QueueController:

@interface QueueController : NSObject<NSURLSessionDelegate>

@property(nonatomic, weak) NSObject<QueueControllerDelegate>* delegate;
@property(atomic, strong) NSURLSession* session;
@property(nonatomic) NSURLSessionConfiguration* configuration;

+ (QueueController*)sharedInstance;

@end

@implementation QueueController {
- (void)application:(UIApplication *)application
handleEventsForBackgroundURLSession:(NSString *)identifier
completionHandler:(void (^)(void))completionHandler {
//...
}

TransferUploadModel:

    @interface TransferUploadModel : TransferModel <NSURLSessionTaskDelegate,
                                                    NSURLSessionDataDelegate>
    //...

    @end    


//Note TransferModel is a subclass of NSOperation
@implementation TransferUploadModel


- (id)initWithMedia:(MediaItem*)mediaItem_
   withTransferType:(TransferType)transferType_
      andWiths3Path:s3Path_
 andWiths3file_name:s3file_name_
andWithNSURLSession:session {
}


- (void)main {
    //NSOperation override
}



//
// Transfer upload started
//
- (void)uploadMedia {
    /**
     * Fetch signed URL
     */
    AWSS3GetPreSignedURLRequest *getPreSignedURLRequest = [AWSS3GetPreSignedURLRequest new];
    getPreSignedURLRequest.bucket = BUCKET_NAME;
    getPreSignedURLRequest.key = @"mypic.jpeg";
    getPreSignedURLRequest.HTTPMethod = AWSHTTPMethodPUT;
    getPreSignedURLRequest.expires = [NSDate dateWithTimeIntervalSinceNow:3600];

    // Important: must set contentType for PUT request
    getPreSignedURLRequest.contentType = self.content_type;
    NSLog(@"headers: %@", getPreSignedURLRequest);

    /**
     * Upload the file
     */
    [[[AWSS3PreSignedURLBuilder defaultS3PreSignedURLBuilder] getPreSignedURL:getPreSignedURLRequest] continueWithBlock:^id(AWSTask *task) {

        if (task.error) {
            NSLog(@"Error: %@", task.error);
        } else {
            NSURL* presignedURL = task.result;
            NSLog(@"upload presignedURL is: \n%@", presignedURL);

            NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:presignedURL];
            request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
            [request setHTTPMethod:@"PUT"];
            [request setValue:self.content_type forHTTPHeaderField:@"Content-Type"];

            @try {
                self.nsurlSessionUploadTask = [self.nsurlSession uploadTaskWithRequest:request
                                                             fromFile:self.mediaCopyURL];
                [self.nsurlSessionUploadTask resume];
                //
                // Delegates don't fire after this...
                //
            } @catch (NSException* exception) {
                NSLog(@"exception creating upload task: %@", exception);
            }
        }
        return nil;
    }];
}


//
// NSURLSessionDataDelegate : didReceiveData
//
- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data {
    NSLog(@"...");
}

//
// Initial response from server with headers
//
- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:
(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    NSLog(@"response.description:%@", response.description);
    completionHandler(NSURLSessionResponseAllow);
}

//
// Upload transfer in progress
//
- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionUploadTask *)task
   didSendBodyData:(int64_t)bytesSent
    totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
    @try {
        NSLog(@"...");
    } @catch (NSException *exception) {
        NSLog(@"%s exception: %@", __PRETTY_FUNCTION__, exception);
    }
}

//
// Upload transfer completed
//
- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error {
        NSLog(@"...");
} // end URLSession:session:task:error


@end

Любая помощь горячо приветствуется.

Спасибо, Дж.


person JT_Dylan    schedule 04.09.2015    source источник


Ответы (1)


Хорошо, я обнаружил, что если я переместил NSURLSession в TransferUploadModel и TransferDownloadModel, то делегаты будут вызваны. Поскольку этих моделей много в очереди, я инициализирую так:

@implementation TransferUploadModel

static NSURLSession *session = nil;
static dispatch_once_t onceToken;

- (id) init {
    self = [super init];
    dispatch_once(&onceToken, ^{
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"transferUploadQueue"];
        configuration.sessionSendsLaunchEvents = YES;
        configuration.discretionary = YES;
        session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    });
    self.session = session;
}

//...

@end

Спасибо, Джон

person JT_Dylan    schedule 04.09.2015