AlexR
AlexR

Reputation: 5634

How to use delegates with NSURLSession

I would like to handle the results of a Twitter request by using delegates (I can't use the default block-based methods).

This is how I have set up my request:

NSArray *twitterAccounts = [self.accountStore 
    accountsWithAccountType:twitterAccountType];
SLRequest *request = [SLRequest 
    requestForServiceType:SLServiceTypeTwitter requestMethod:
    SLRequestMethodGET URL:url parameters:params];
request.account = twitterAccounts.lastObject;

NSURLSessionDataTask *dataTask = [[NSURLSession 
    sharedSession] dataTaskWithRequest:[request 
    preparedURLRequest]];
[dataTask resume];

Question:

How can I specify that I want to handle the response by using delegation? Unfortunately, there is no delegate property on NSURLSessionDataTask and its related classes.

Upvotes: 0

Views: 237

Answers (1)

David Berry
David Berry

Reputation: 41226

To me it's cleaner to embed the blocks so you can see exactly what the flow is, but to each his own.

In this case you can fake delegation by using a block to invoke any method you want.

You could subclass NSURLSessionDataTask to add a delegate property and automatically add the right blocks to invoke appropriate delegate methods. Block proponents have been using the opposite approach for years to turn delegate-based callbacks into block-based callbacks :)

Upvotes: 2

Related Questions