我正在从Web服务API下载数据。在我的项目中,我必须在很多地方使用不同的API下载数据。因此,每当Iam调用Web服务时,这都会导致代码的复杂性。
- (void)downloadInvitedVcards
{
AppManager *oAppManager = [AppManager getSharedInstance];
[oAppManager hasreachabilityChanged];
if (oAppManager.currentConnectivity) {
//NSString *deviceUDID = oAppManager.deviceID;
NSArray *keys = [NSArray arrayWithObjects:@"UserName",@"PMobileNo",nil];
NSArray *objects = [NSArray arrayWithObjects:oAppManager.userName,oAppManager.mobileno,nil];
NSData *_jsonData = nil;
NSString *_jsonString = nil;
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
if ([NSJSONSerialization isValidJSONObject:jsonDictionary]) {
_jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
_jsonString = [[NSString alloc] initWithData:_jsonData encoding:NSUTF8StringEncoding];
}
NSString *newUrl = oAppManager.loginURL;
NSString *appendUrl = [newUrl stringByAppendingString:@"/DownloadInvitedVcards"];
NSURL *aUrl = [NSURL URLWithString:appendUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:_jsonData];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d",[_jsonData length]] forHTTPHeaderField:@"Content-Length"];
NSError *errorReturned = nil;
NSURLResponse *theResponse = [[NSURLResponse alloc] init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
NSLog(@"Error %@",errorReturned);
}
else {
NSString *responseString = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@",responseString);
NSArray *responseData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
for (NSDictionary *resultData in responseData) {
NSLog(@"Value :%@",resultData);
}
}
}
}
whererever required Iam执行相同的过程但更改了API方法。它工作正常,但这会导致更多代码和复杂性增加。有没有更好的方法来实现这一目标。
答案 0 :(得分:0)
听起来你的问题不仅仅是代码问题。我将研究创建一个单独的类,其作用是简单地管理来往服务器的请求。它将结束所有提出请求,序列化结果等的机制。然后你的应用程序的其余部分只需要它检索他们想要的数据或将他们的请求转发给服务器。