iosobjective-casihttprequestasiformdatarequest

ASIHTTPRequest async request in model class


I want to use ASIHTTPRequest or ASIFormDataRequest in my model class. How can I delegate or detect request status, and return value.

Such as:

I've a Controller having IBAction DoIt:sender. I want to call Connector->DoIt and call my Controller back when connection successfull or fail.

How can I handle it?

Thank you.


Solution

  • Callback based (from documentation):

    - (IBAction)grabURLInBackground:(id)sender
    {
       NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
       ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
       [request setDelegate:self];
       [request startAsynchronous];
    }
    
    - (void)requestFinished:(ASIHTTPRequest *)request
    {
       // Use when fetching text data
       NSString *responseString = [request responseString];
    
       // Use when fetching binary data
       NSData *responseData = [request responseData];
    }
    
    - (void)requestFailed:(ASIHTTPRequest *)request
    {
       NSError *error = [request error];
    }
    

    Block based:

    - (IBAction)grabURLInBackground:(id)sender
    {
       NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
       __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
       [request setCompletionBlock:^{
          // Use when fetching text data
          NSString *responseString = [request responseString];
    
          // Use when fetching binary data
          NSData *responseData = [request responseData];
       }];
       [request setFailedBlock:^{
          NSError *error = [request error];
       }];
       [request startAsynchronous];
    }