user1994291
user1994291

Reputation:

Sending AsynchronousRequest with a block-the right way

In my app i am sending a request to server . The request is in some other class-called requestClass, and is being called from the main view class. (i am using cocos2d).

My question is, how would i informed the main class (from the requestClass ) that the operation is done ? When it finish the request-its callback is in its own class(requestClass) and the NSLog is done IN the requestClass .

i dont think NSNotification is the right way

requestClass is like :

[NSURLConnection
     sendAsynchronousRequest:request
     queue:[[NSOperationQueue alloc] init]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {

         if ([data length] >0 && error == nil)
         {
             **// HOW SHOULD I INFORM THE CLASS THAT CALL ME NOW ???**

         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing ");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }

     }];

Upvotes: 0

Views: 39

Answers (1)

Fogmeister
Fogmeister

Reputation: 77631

OK, to write a delegate protocol...

Assuming your connection file is called MyRequestClass.

In MyRequestClass.h...

@protocol MyRequestClassDelegate <NSObject>

- (void)requestDidFinishWithDictionary:(NSDictionary*)dictionary;

//in reality you would pass the relevant data from the request back to the delegate.

@end

@interface MyRequestClass : NSObject // or whatever it is

@property (nonatomic, weak) id <MyRequestClassDelegate> delegate;

@end

Then in MyRequestClass.h

[NSURLConnection
     sendAsynchronousRequest:request
     queue:[[NSOperationQueue alloc] init]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {

         if ([data length] >0 && error == nil)
         {
             [self.delegate requestDidFinishWithDictionary:someDictionary];

             //you don't know what the delegate is but you know it has this method
             //as it is defined in your protocol.
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing ");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }

     }];

Then in whichever class you want...

In SomeOtherClass.h

#import "MyRequestClass.h"

@interface SomeOtherClass : UIViewController <MyRequestClassDelegate>

blah...

In someOtherClass.m

MyRequestClass *requestClass = [[MyRequestClass alloc] init];

requestClass.delegate = self;

[requestClass startRequest];

... and make sure to write the delegate function too...

- (void)requestDidFinishWithDictionary:(NSDictionary*)dictionary
{
    //do something with the dictionary that was passed back from the URL request class
}

Upvotes: 1

Related Questions