ASIHTTPRequest Code Development

I use ASIHTTPRequest for asynchronous communication with the server. It works fine, but I execute requests in different controllers, and now duplicate methods are in all of these controllers. What is the best way to abstract this code (queries) into one class, so I can easily reuse the code, so I can keep the controllers simpler. I can put it in singleton (or in the application delegate), but I don't think this is a good approach. Or maybe create for me my own protocol with a delegate callback.

Useful tips for good design. Thanks.

+3
source share
3 answers

I use Ben Copsey subclasses ASIHTTPRequestvery much for the web service client that I hope to finish in the next couple of weeks. This is a great project, and his work saved me a lot of time and effort.

I have ASINetworkQueueinstalled in the application deletion. The queue is sent -goso that it is ready to receive requests. I add my subclasses to this queue. Each request is processed and issues notifications, and my view controller processes the corresponding response data.

What I did is subclass ASIHTTPRequestand:

  • Set up the method -init(or -initWithParams:method, depending on the request)
  • Override -requestFailed:and -requestCompleted:to handle HTTP error messages returned from the web service
  • NSNotification, -requestCompleted:

, . .

NSNotification UIAlertView, , - , (, ), HTTP.

, -release , .

+7

, .

static  TCHttpRequest *_sharedHttpRequest = nil;
+ (id)sharedRequest
{
    @synchronized(self){
        if (_sharedHttpRequest == nil) {
            _sharedHttpRequest = [[self alloc] init];
        }
    }
    return  _sharedHttpRequest;
}


- (NSDictionary *)loginWithUserName:(NSString *)user password:(NSString *)pwd
{
    NSURL *url = [NSURL URLWithString:@"/login" relativeToURL:_url];

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setCachePolicy:ASICacheForSessionDurationCacheStoragePolicy];
    [request setTimeOutSeconds:HTTP_REQ_TIMEOUT];
    [request addPostValue:user forKey:@"username"];
    [request addPostValue:pwd forKey:@"password"];
    request.delegate = self.delegate;
    [_common_queue addOperation:request];
}
0

I don’t see how the class method and instance method are related? The class method creates an instance of TCHttpRequest and guarantees only one instance. The loginWithUserName instance method creates an ASIFormDataRequest instance and adds it to the public queue. I do not see reuse here?

0
source

Source: https://habr.com/ru/post/1723100/


All Articles