Следующие шаги предназначены для интеграции json in в наш проект.
1) Скопируйте вставьте этот файл в свой проект.
2) Создайте новое имя группы в качестве справки, содержащей следующие файлы.
3) Создать новый файл в поддержку файлов, которое имя как constant.h
#define WEB_SERVICE_URL @"Your server url" //@"http://demo.google.com/webservice/"
#define USERNAME @"Your user id"//static username to send everytime
#define PASSWORD @"Your Password"//static password to send everytime
4) Измените выше переменной ссылку, где находится ваш веб-сервис существует, что означает, что адрес вашего веб-сервиса «WEB_SERVICE_URL "
5) Откройте файл« Rest.h »и создайте один метод.
-(void)Get_StoreDetails:(SEL)seletor andHandler:(NSObject*)handler andCountryId:(NSString *)CountryCode;
6) Открыть файл «Rest.m» и какой аргумент передать серверу этот метод для кодирования.
-(void)Get_StoreDetails:(SEL)seletor andHandler:(NSObject *)handler andCountryId:(NSString *)country_id{
NSDictionary *req = [NSDictionary dictionaryWithObjectsAndKeys:@"content/get_stores",@"request",
[NSDictionary dictionaryWithObjectsAndKeys:USERNAME,@"username",
PASSWORD,@"password",
country_id,@"country_id",
nil],@"para",nil];
[[[JSONParser alloc] initWithRequest:req sel:seletor andHandler:handler] autorelease];
}
7) теперь приложение Rest готово для отправки запроса, а затем в настоящее время этот метод вызова в наш контроллер представления.
После кода поместить в метод «viewWillAppear» в файле .h
#import <UIKit/UIKit.h>
@interface JsonDemoAppViewController : UIViewController{
UIAlertView *alertCtr;
}
@property(nonatomic,retain)NSMutableArray *arrForStores;
- (void)getData:(id)object;
@end
следующий код помещается в метод «viewWillAppear» в .m файл и импорта «Rest.h».
- (void)viewWillAppear:(BOOL)animated {
self.arrForStores=nil;
//============================Json Initialization===================================================
REST *rest = [[REST alloc] init];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[rest Get_StoreDetails:@selector(getData:) andHandler:self andCountryId:@"12"];
alertCtr = [[[UIAlertView alloc] initWithTitle:@"\nPlease Wait..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil] autorelease];
[alertCtr show];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
// Adjust the indicator so it is up a few pixels from the bottom of the alert
indicator.center = CGPointMake(alertCtr.bounds.size.width/2, alertCtr.bounds.size.height - 50);
[indicator startAnimating];
[alertCtr addSubview:indicator];
[indicator release];
//===================================================================================================
}
Тогда ответ приходит на сервер, чтобы хранить объект времени в переменную, чтобы мы создали метод, который вызывает.
- (void)getData:(id)object{
NSLog(@"%@",object);
if ([object isKindOfClass:[NSDictionary class]]) {
NSLog(@"Controll comes here..");
//IF your response type is NSDictionary then this code to run
}
if ([object isKindOfClass:[NSArray class]])
{
self.arrForStores=[NSArray arrayWithArray:(NSArray*)object];
//IF your response type is NSArray then this code to run
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
[alertCtr dismissWithClickedButtonIndex:0 animated:YES];
}
Download the source code From Here
Проверить этот учебник - http://www.raywenderlich.com/5492/working-with-json-in-ios-5 – rishi
@RIP: Я проверил этот учебник, но я не знаю, как и где передавать параметры. В этом учебном руководстве только URL-адрес передается из приложения. –