开发者

How do I repeat an ASIHTTPRequest?

Given the example code below:

// ExampleModel.h

@interface ExampleModel : NSObject <ASIHTTPRequestDelegate> {

}

@property (nonatomic, retain) ASIFormDataRequest *request;
@property (nonatomic, copy) NSString *iVar;

- (void)sendRequest;


// ExampleModel.m

@implementation ExampleModel

@synthesize request;
@synthesize iVar;

# pragma mark NSObject

- (void)dealloc {
    [request clearDelegatesAndCancel];
    [request release];
    [iVar release];
    [super dealloc];
}

- (id)init {
    if ((self = [super init])) {
        // These parts of the request are alw开发者_运维问答ays the same.
        NSURL *url = [[NSURL alloc] initWithString:@"https://example.com/"];
        request = [[ASIFormDataRequest alloc] initWithURL:url];
        [url release];
        request.delegate = self;
        [request setPostValue:@"value1" forKey:@"key1"];
        [request setPostValue:@"value2" forKey:@"key2"];
    }
    return self;
}

# pragma mark ExampleModel

- (void)sendRequest {
    // Reset iVar for each repeat request because it might've changed.
    [request setPostValue:iVar forKey:@"iVarKey"];
    [request startAsynchronous];
}

@end

# pragma mark ASIHTTPRequestDelegate

- (void)requestFinished:(ASIHTTPRequest *)request {
    // Handle response.
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    // Handle error.
}

When I do something like [exampleModel sendRequest] from a UIViewController, it works! But, then I do [exampleModel sendRequest] again from another UIViewController and get:

Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '*** -[NSOperationQueue addOperation:]:
operation is finished and cannot be enqueued`

How can I fix this?


You shouldn't attempt to reuse the request object. It maintains state. Really designed to be disposed off after the request is over.

The design isn't as clean as the NSURLConnection, NSURLRequest, NSURLResponse classes (basically mashing all three into one and wrapping the low level core foundation classes underneath). It's still far better than using NSURLConnection in a vanilla fashion if you need to deal with low level HTTP stuff. If you don't, the high level classes have some advantages (like access to the same cache the UIWebView uses).


I think I found the answer: https://groups.google.com/d/msg/asihttprequest/E-QrhJApsrk/Yc4aYCM3tssJ


ASIHTTPRequest and its subclasses conform to the NSCopying protocol. Just do this:

 ASIFormDataRequest *newRequest = [[request copy] autorelease];
 [newRequest startAsynchronous];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜