Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for finish dataTaskWithRequest?

How can I wait for finish of dataTaskWithRequest ? I need to perform some tasks after network fetch is completely over.

like image 270
Alexey K Avatar asked Oct 15 '15 12:10

Alexey K


2 Answers

If you really need synchronous request, you can use semaphores.

I've implemented a small category on NSURLSession to provide this functionality.

In .h file:

@import Foundation.NSURLSession;

@interface NSURLSession (Additions)

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;

@end

In .m file:

@implementation NSURLSession (Additions)

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse *__autoreleasing *)responsePointer error:(NSError *__autoreleasing *)errorPointer
{
    dispatch_semaphore_t semaphore;
    __block NSData *result = nil;

    semaphore = dispatch_semaphore_create(0);

    void (^completionHandler)(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error);
    completionHandler = ^(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error)
    {
        if ( errorPointer != NULL )
        {
            *errorPointer = error;
        }

        if ( responsePointer != NULL )
        {
            *responsePointer = response;
        }

        if ( error == nil )
        {
            result = data;
        }

        dispatch_semaphore_signal(semaphore);
    };

    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:completionHandler] resume];

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    return result;
}

@end
like image 167
Dennis Pashkov Avatar answered Sep 27 '22 23:09

Dennis Pashkov


I think, that method is obvious inside the class

NSURLSessionDataTask *task = [defaultSession dataTaskWithRequest:request
                                               completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
{
    // code after completion of task
}];
[task resume];
like image 40
katleta3000 Avatar answered Sep 27 '22 23:09

katleta3000