Cannot Get ASIHTTPRequest callback delegate to tri

2019-03-04 13:03发布

问题:

Why does my callback delegate not trigger:

#import "dbConnector.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h";

@implementation dbConnector

//method to 
+(void)getQuestions:(NSString*)sectionId{
    NSString* url = @"http://dev.speechlink.co.uk/David/tester.php";
    NSURL *link = [NSURL URLWithString:url];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link]; 
    [request setPostValue:sectionId forKey:@"section"]; 
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestFinished:)];
    [request startAsynchronous];    
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    //NSString *response = [request responseString];
    NSLog(@"hello"); //never prints
}

@end


#import "ASITesterViewController.h"
#import "dbConnector.h";

@implementation ASITesterViewController
@synthesize questions;

-(void)viewDidLoad{
    //code to initialise view
    [dbConnector getQuestions:@"2"];
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

@end

Minus the corresponding header files and the appropriate ASIHTTPRequest Files, these are the only two files I have.. What am I doing wrong?

回答1:

It will not get called b/c you created a class method so it does not have an access to the selector method.

+(void)getQuestions:(NSString*)sectionId

Use synchronic call:

+(void)getQuestions:(NSString*)sectionId{
    NSString* url = @"http://dev.speechlink.co.uk/David/tester.php";
    NSURL *link = [NSURL URLWithString:url];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link]; 
    [request setPostValue:sectionId forKey:@"section"];   

    [request startSynchronous];

    NSError *error = [request error];
    if (!error) {
        //Do what you want with the response
    }else{
        //Error
    }

}

EDIT 2 Pass a delegate parameter to the function.

+(void)getQuestions:(NSString*)sectionId respondToDelegate:(id)delegate{
    NSString* url = @"http://dev.speechlink.co.uk/David/tester.php";
    NSURL *link = [NSURL URLWithString:url];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link]; 
    [request setPostValue:sectionId forKey:@"section"]; 
    [request setDelegate:delegate];
    [request setDidFinishSelector:@selector(requestFinished:)];
    [request startAsynchronous];    
}


回答2:

The part about your code I'm not certain of is putting the request trigger in a class method of a different class. Do you know that [dbConnector getQuestions:@"2"]; is actually firing the intended method?