如何使用NSURLConnection委托方法处理多个请求?

时间:2015-08-18 05:08:39

标签: ios json nsurlconnectiondelegate

我有两个网络服务,我想从中解析数据,我在下面编写了正确的数据。

现在,我的问题是,如果我有10个webservices,那么我必须创建10个NSURLConnection对象? 这还不够。我确信还有其他方法可以使用NSURL连接委托方法管理多个请求。

如果您知道,请帮助我改进我的代码。

#import "ViewController.h"

@interface ViewController ()
{
                NSURLConnection *conn ;
                NSURLConnection *conn1 ;
}
@end

@implementation ViewController

- (void)viewDidLoad {
      [super viewDidLoad];

         // Create the request.
         NSURL *pathUrl = [NSURL URLWithString:@"http://inheritxdev.net/hapzz_live/getpostsbylocation"];

         NSString *strParameter = @"{\"auth_token\":\"3b7a34b7e1f33bde27d9b335f02b839d\",lattitude:\"23.041261\",longitude:\"72.513892\",\"user_id\":\"60\"}";

         NSMutableURLRequest *requestUrl = [NSMutableURLRequest requestWithURL:pathUrl];
         [requestUrl setHTTPMethod:@"POST"];
         [requestUrl setHTTPBody:[strParameter dataUsingEncoding:NSUTF8StringEncoding]];

                // Create url connection and fire request
         conn = [[NSURLConnection alloc] initWithRequest:requestUrl delegate:self];

        if( conn )
         {
               responseData = [[NSMutableData alloc] init];
         }


        NSURL *url1 = [NSURL URLWithString:@"http://admin.pelloapp.com/index.php?postlist"];
        NSString *body = @"{\"user_id\": \"64\",\"page\":\"1\"}";

        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url1];
       [urlRequest setHTTPMethod:@"POST"];
       [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];

       conn1 = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];

       if( conn1 )
       {
                    responseData1 = [[NSMutableData alloc] init];
       }

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
       if (connection == conn)
       {
             [responseData setLength:0];
      }
      else
     {
             [responseData1 setLength:0];
     }
}

 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
 {
         if (connection == conn)
         {
             [responseData appendData:data];
         }
         else
         {
             [responseData1 appendData:data];
         }
}

 - (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                              willCacheResponse:(NSCachedURLResponse*)cachedResponse
{
        return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
      // NSLog(@"connectionDidFinishLoading");
      if (connection == conn)
       {
            NSError *error = nil;

         //parsing the JSON response
        id jsonObject = [NSJSONSerialization
                                 JSONObjectWithData:responseData
                                 options:NSJSONReadingAllowFragments
                                 error:&error];

               NSLog(@"%@", jsonObject);
       }
       else
       {
             NSError *error = nil;

            //parsing the JSON response
            id jsonObject = [NSJSONSerialization
                                     JSONObjectWithData:responseData1
                                     options:NSJSONReadingAllowFragments
                                     error:&error];

                    NSLog(@"%@", jsonObject);
        }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
      NSLog(@"error = %@", error);
}

1 个答案:

答案 0 :(得分:4)

为它创建JSONParser类&将协议声明为。

在.h文件中

@protocol  JSONParserDelegate <NSObject>

@required
- (void)DidBegin;
- (void)DidFail:(NSString *)errorstr;
- (void)DidFinish:(id)data;

@end

@interface JSONParser : NSObject
{
id json;
NSURLConnection *connection;
NSMutableData *responseData;

}
@property (nonatomic, weak) id <JSONParserDelegate> delegate;
@property (nonatomic, strong) NSString *str_ServiceName;

-(void)parseData:(NSDictionary *) dict WebServiceName:   (NSString*)WebserviceString;

@end

&安培;在.m文件中

@implementation JSONParser
@synthesize delegate;
@synthesize str_ServiceName;

-(void)parseData:(NSDictionary *)dict WebServiceName:(NSString*)WebserviceString
{

  NSLog(@"WebserviceString---%@",WebserviceString);
  NSLog(@"dict::%@",dict);

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:  [NSURL URLWithString:WebserviceString]];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
//Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
[request setHTTPBody:postData];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
   responseData = [NSMutableData data];

 }

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData  *)data
 {
   [responseData appendData:data];

 }

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
id data= [NSJSONSerialization  JSONObjectWithData:responseData  options:kNilOptions error:&error];
NSMutableDictionary * ResponseDictionary =(NSMutableDictionary*)data;
//NSLog(@"response data - %@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
NSLog(@" error: %@", error);
[self DidFinish:ResponseDictionary];

  }

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
 {
NSLog(@"error %@",error);
[self DidFail:error.localizedDescription];
 }

- (void)DidBegin
{

}

- (void)DidFail:(NSString *)errorstr
{
if (delegate && [delegate respondsToSelector:@selector(DidFail:)])
{
    [delegate DidFail:errorstr];
}
}

- (void)DidFinish:(id)data 
{
//encrypted data
if (delegate && [delegate respondsToSelector:@selector(DidFinish:)])
{
   // [data setObject:str_ServiceName forKey:@"ServiceName"];

    NSLog(@" data - %@",data);
    [delegate DidFinish:data];
}
}

&安培;在您的视图控制器类中调用webservice方法为

 NSDictionary  *dictWithObjectAndKey =[[NSDictionary alloc]initWithObjectsAndKeys:POS_DEV3_MERCHANT,@"MerchantID",txt_searchCustomer.text,@"SearchText",@"0",@"StartIndex",@"0",@"EndIndex",nil];

NSLog(@"dictWithObjectAndKey===%@",dictWithObjectAndKey);
obj_json =[[JSONParser alloc]init];
[obj_json parseData:dictWithObjectAndKey WebServiceName:GET_CUSTOMER_DETAILS];
obj_json.delegate=self;

&安培;实现委托方法

- (void)DidBegin
{

}

- (void)DidFail:(NSString *)errorstr
{
[activityIndicator unloadActivityIndicatorView:self.view];
}

- (void)DidFinish:(id)data
{
}