我正在使用ASIFormDataRequest框架来使用服务器端请求和响应。我不希望每个视图控制器类使用请求和响应方法。我想为服务处理函数使用单独的单例类,然后该类正确地触发服务成功和失败。我在ios项目中实现了这个想法。
但是,我一次做了多个请求,然后我无法得到我请求的响应。请仔细阅读以下代码。在此代码中,我在service handle
类中使用自定义委托。我认为,当一次完成多个请求时,可能会更改此自定义委托方法。
注意:来自不同视图控制器的多个请求。
ServiceHandle.h
@protocol serviceDelegate <NSObject>
-(void)successFullResponse:(ASIHTTPRequest *)req;
-(void)failedResponse:(ASIHTTPRequest *)req;
@end
@interface ServiceHandle : NSObject
@property(nonatomic,strong)NSOperationQueue *queue;
@property (nonatomic,weak)id<serviceDelegate>delegate;
+ (id)sharedInstance;
-(void)loginWithUserName:(NSString *)userName;
-(void)userReg:(NSDictionary*)userDict;
@end
ServiceHandle.m
static ServiceHandle *sharedInstance = nil;
@implementation ServiceHandle
@synthesize delegate,queue;
+(ServiceHandle *)sharedInstance{
if (sharedInstance == nil) {
sharedInstance = [[super allocWithZone:NULL]init];
}
return sharedInstance;
}
- (id)init
{
self = [super init];
if (self) {
// Work your initialising magic here as you normally would
}
return self;
}
-(void)loginWithUserName:(NSString *)userName{
if (![self queue]) {
[self setQueue:[[NSOperationQueue alloc] init]];
}
NSString *path=[NSString stringWithFormat:@"%@userLogin",webserviceURL];
NSString *lattitude=[[NSUserDefaults standardUserDefaults] objectForKey:@"mylatitude"];
NSString *longitude=[[NSUserDefaults standardUserDefaults] objectForKey:@"mylongitude"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:path]];
[request setTimeOutSeconds:30];
[request setPostValue:userName forKey:@"userId"];
[request setPostValue:lattitude forKey:@"latitude"];
[request setPostValue:longitude forKey:@"longitude"];
[request setShouldContinueWhenAppEntersBackground:YES];
[request setDidFinishSelector:@selector(requestSuccess:)];
[request setDidFailSelector:@selector(requestFail:)];
request.queuePriority = NSOperationQueuePriorityHigh;
request.delegate = self;
[[self queue]addOperation:request];
}
-(void)requestSuccess:(ASIHTTPRequest *)request{
if ([self.delegate respondsToSelector:@selector(successFullResponse:)]) {
[self.delegate successFullResponse:request];
}
}
-(void)requestFail:(ASIHTTPRequest *)request{
if ([self.delegate respondsToSelector:@selector(failedResponse:)]) {
[self.delegate failedResponse:request];
}
}
ViewController.m
-(IBAction)clickLogin:(id)sender{
ServiceHandle *sharedObj = [ServiceHandle sharedInstance];
sharedObj.delegate = self;
[sharedObj loginWithUserName:@“usrName”];
}
-(void)successFullResponse:(ASIHTTPRequest *)req{
NSString *responseString = [req responseString];
NSLog(@"responseString is%@",responseString);
NSDictionary *responseDict = [responseString JSONValue];
NSLog(@"dict is :%@",responseDict);
}
-(void)failedResponse:(ASIHTTPRequest *)req{
}