如何使用 NSURLConnection 委托方法处理多个请求?
How to handle multiple request using NSURLConnection delegate method?
我有两个 web 服务,我想从中解析数据,我在下面编写了代码,我从中正确地获取了数据。
现在,我的问题是,如果我有 10 个 Web 服务,那么我必须创建 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);
}
为其创建 JSONParser class 并在其中声明协议为。
在 .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];
}
}
& 在你的视图控制器中 class 调用网络服务方法
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
{
}
我有两个 web 服务,我想从中解析数据,我在下面编写了代码,我从中正确地获取了数据。
现在,我的问题是,如果我有 10 个 Web 服务,那么我必须创建 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);
}
为其创建 JSONParser class 并在其中声明协议为。
在 .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];
}
}
& 在你的视图控制器中 class 调用网络服务方法
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
{
}