1

我正在使用 ASIFormDataRequest 框架来使用服务器端请求和响应。我不想在每个视图控制器类中使用请求和响应方法。我想为服务处理功能使用一个单独的单例类,然后该类正确触发服务成功和失败。我在我的 ios 项目中实现了这个想法。

但是一次完成多个请求,然后我无法得到我请求的正确响应。请浏览我的以下代码。在此代码中,我在service handle课堂上使用自定义委托。我认为当一次完成多个请求时,这个自定义委托方法可能会改变。

注意:一次来自不同视图控制器的多个请求。

服务句柄.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

服务句柄.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];
  }
}

视图控制器.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{


  }
4

0 回答 0