json status is not entering in if - ios

i have this method to login via json array , it's all ok but it's not entering in
if(json2 == 0)
but in NSLog show me that it's value is 0 , how can i resolve this ? the method is working but it doesent enter in that if.
-(void)loginAPICall
{
NSString *device_name = #"Iphone";
NSString *device_modelname = #"5";
NSString *gcm_id = #"1234567890";
NSString *user = _user.text;
NSString *pass = _pass.text;
// SENDING A POST JSON
NSString *post = [NSString stringWithFormat:#"device_name=%#&device_modelname=%#&gcm_id=%#&username=%#&password=%#", device_name, device_modelname, gcm_id, user, pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[[NSURL alloc] initWithString:#"http://192.168.1.110/project/api"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSError *error;
NSMutableDictionary *getJsonData = [NSJSONSerialization
JSONObjectWithData:requestHandler
options:NSJSONReadingMutableContainers
error:&error];
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
else {
NSArray *json = getJsonData[#"login"];
for ( NSDictionary *jsn in json )
{
NSLog(#"id: %# ", jsn[#"id_user"] );
}
NSArray *json2 = getJsonData[#"status"];
if(json2 == 0){
NSLog(#"Cannot login");
}
NSLog(#"value:%#",json2);
}
}

You are saying that the object return by getJsonData[#"status"]; is an array, but then you are check if with an integer :
NSArray *json2 = getJsonData[#"status"];
if(json2 == 0){
NSLog(#"Cannot login");
}
If you need to check whether the array return by status has values do it like thisL:
NSArray *json2 = getJsonData[#"status"];
if([json2 count] == 0){
NSLog(#"Cannot login");
}
If the object return for the node status is an integer then try this:
NSNumber *json2 = getJsonData[#"status"];
if([json2 integerValue] == 0){
NSLog(#"Cannot login");
}

Related

iOS - different response from single API in ARC and parsing

In my project i am passing this API: http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat with params: prod_id=25,var_id=140.
The problem is when i am pass this api in Rest Client it displays correct response but when i am trying to put it in my code it shows different response.
i am using the following code:
-(void)listofNotice
{
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
//NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
}
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
}
else
{
return jsonObject;
}
}
it display the following response:
str : {
business = 0;
"business-list" = "Business list empty.";
response = 401;
}
but the actual response is something like this
please help me.. Thanks In advance
Please change this
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
To:
NSString * post =[NSString stringWithFormat:#"prod_id=25&var_id=140"];
if possible use this:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.HTTPAdditionalHeaders = #{#"application/x-www-form-urlencoded" : #"Content-Type"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [post dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (data != nil){
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
NSLog(#"Status Code: %ld", (long)code);
if (code == 200) {
NSError *error;
id responseObject =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
}
}
}];
[postDataTask resume];
OR
NSString *postString = [NSString stringWithFormat:#"prod_id=%#&var_id=%#",#"25",#"140"];
NSURL *urlPath = [NSURL URLWithString:#"http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlPath
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSData *requestData = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
[APP_DELEGATE removeLoader];
if(data != nil) {
NSDictionary *responseObject =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#" %#", responseObject);
}
else {
}
}];
Hope this helps.
I think you need to change below code
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
to
NSDictionary *prodDict=#{#"prod_id":#"25",
#"var_id":#"140"};

How to perform a GET request and check the response

I have a NSString which contains the URL. I want to make a GET request using the URL and also check if the response is 200.
With the current code i get response as 0.
Here is my code:
NSString *Url = #"http://www.xyx.com";
NSData *data = [Url dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *len = [NSString stringWithFormat:#"%lu", (unsigned long)[data length]];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc]init];
[req setURL:[NSURL URLWithString:Url]];
[req setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:req completionHandler:^(NSData data, NSURLResponse response, NSError *error) {
NSString *req = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"Reply = %#", req);
}]resume];
use this code it works for you:
-(void)yourMethodNAme
{
NSString *post = #"";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"Your URL"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
//NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
//NSLog(#"str : %#",dict6);
}
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
}
else
{
return jsonObject;
}
}
and finally call it in ViewDidLoad as [self yourMethodNAme];
-(void) httpGetWithCustomDelegateWithString: (NSString*)urlString
{
[self startActivity];
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:urlString];
NSURLSessionDataTask *dataTask =[defaultSession dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(#"Response:%# %#\n", response, error);
if(error == nil)
{
//NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
//NSLog(#"Data = %#",text);
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
deserializedDictionary = nil;
if (jsonObject != nil && error == nil)
{
if ([jsonObject isKindOfClass:[NSDictionary class]])
{
//Convert the NSData to NSDictionary in this final step
deserializedDictionary = (NSDictionary *)jsonObject;
NSLog(#"dictionary : %#",deserializedDictionary);
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
deserializedArr = (NSArray*)jsonObject;
NSLog(#"array : %#",deserializedArr);
}
}
[self setAlert];
}
else
{
[activityView removeFromSuperview];
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
[self showAlert:#"Error" :#"Network error occured." :#"Ok"];
}
}];
[dataTask resume];
}
just use the above code and call it by
[self httpGetWithCustomDelegateWithString:#"webStringHere"];
On Completion, it will call the method -(void)setAlert; so declare it in your class where you use this.
This may be due to App Transport Security blocking HTTP.
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
Try making a request to a secure site (e.g. https://www.google.com) as a test.

How to differanitate data from json when the data is in two dictionaries?

I am fetching data from JSON. It gives response in two dictionaries. How to differentiate that dictionaries and paste the data in table view. I am using segment control in table view. One is for receiver and other is for sender.
NSUserDefaults *uidSave = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *get = [[NSMutableDictionary alloc]init];
[get setObject:[uidSave valueForKey:#"uid"]forKey:#"uid"];
NSLog(#"Dictionary Data which is to be get %#",get);
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:get options:kNilOptions error:nil];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [[NSString alloc]initWithFormat:#"r=%#",jsonInputString];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#",caseInfoUrl]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (responseData != nil)
{
jsonArray = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"Values =======%#",jsonArray);
sender = [jsonArray objectForKey:#"sender"];
NSLog(#"Sender^^^^%#",sender);
receiver = [jsonArray objectForKey:#"reciever"];
NSLog(#"Reciever$$$$%#",receiver);
}
if (error)
{
NSLog(#"error %#",error.description);
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Server not responding" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil, nil];
[alertView show];
}
// Set up names array
sendArray = [[NSMutableArray alloc]init];
// Loop through our json Array
for (int i = 0 ; i <sender.count; i++)
{
//create object
NSString *dateTime = [[sender objectAtIndex:i]objectForKey:#"datetime"];
NSString *proNumber = [[jsonArray objectAtIndex:i]objectForKey:#"pro_number"];
NSString *statuses = [[jsonArray objectAtIndex:i]objectForKey:#"status"];
[sendArray addObject:[[DataObjects alloc]initWithDate1:dateTime andCaseName1:proNumber andStatus1:statuses]];
}
[sendList reloadData];
}
Define a BOOL variable
BOOL senderSectionIsSelected;
If you want to load sender's data initially then in ViewDidLoad:-
senderSectionIsSelected=YES;
If you want to load receiver's data then set it to NO;
senderSectionIsSelected=NO;
Modify this
if (responseData != nil)
{
jsonArray = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"Values =======%#",jsonArray);
sender = [jsonArray objectForKey:#"sender"];
NSLog(#"Sender^^^^%#",sender);
receiver = [jsonArray objectForKey:#"reciever"];
NSLog(#"Reciever$$$$%#",receiver);
[yourTableView reloadData];
}
In your numberOfRow and cellForRow load data accordingly:-
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (senderSectionIsSelected)
{
return sender.count;
}
else
{
return receiver.count;
}
}
In cellForRow show data accordingly:-
if (senderSectionIsSelected)
{
yourDataTimeLabel.text=[[sender objectAtInder:indexPath.row]objectForKey:#"datetime"];
yourProNumberLabel.text=[[sender objectAtInder:indexPath.row]objectForKey:#"pro_number"];
yourStatusLabel.text=[[sender objectAtInder:indexPath.row]objectForKey:#"status"];
}
else
{
yourDataTimeLabel.text=[[receiver objectAtInder:indexPath.row]objectForKey:#"datetime"];
yourProNumberLabel.text=[[receiver objectAtInder:indexPath.row]objectForKey:#"pro_number"];
yourStatusLabel.text=[[receiver objectAtInder:indexPath.row]objectForKey:#"status"];
}
Now in your segmentController's action methods:-
If its segment for sender then:-
senderSectionIsSelected=YES;
If its segment for receiver then:-
senderSectionIsSelected=NO;
//don't forget to reload tableView
senderSectionIsSelected=YES;

Using JSON to store data inside a variable

Good afternoon,
I'm trying to store the response from a JSON output because I want to show in a "ProfileViewController" the stats of the users and I'm trying to use the following function in order to store the information.
At the moment the output is fine, because the data is OK depending on the users, but now I have to store each one of the stats in a "variable" for each of the stats (I have 3) but when I run the code it didn't show my NSLog for Stars, Followers and Pictures...
Can you help me with that? The response is fine, now I just want to store each one of the stats in a single variable. How can I do that? What's wrong in my code?
ProfileViewController -> fetchJson:
-(void)fetchJson {
NSString *usersPassword = [SSKeychain passwordForService:#"login" account:#"account"];
NSString *post =[[NSString alloc] initWithFormat:#"usersPassword=%#",usersPassword];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://website.com/profile.php"];
NSData * data = [NSData dataWithContentsOfURL:url];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
NSLog(#"%ld",(long)success);
if(success == 1)
{
NSLog(#"Login SUCCESS");
[_jsonArray removeAllObjects];
_jsonArray = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
for(int i=0;i<_jsonArray.count;i++)
{
NSDictionary * jsonObject = [_jsonArray objectAtIndex:i];
NSString* stars = [jsonObject objectForKey:#"stars"];
NSLog(#"Stars ==> %#", stars);
NSDictionary * jsonObject2 = [_jsonArray objectAtIndex:i];
NSString* followers = [jsonObject2 objectForKey:#"followers"];
NSLog(#"Followers ==> %#", followers);
NSDictionary * jsonObject3 = [_jsonArray objectAtIndex:i];
NSString* photos = [jsonObject3 objectForKey:#"photos"];
NSLog(#"Pictures ==> %#", photos);
}
}
}
}
JSON output:
{"success":1,"stars":50,"photos":50,"followers":50}
Thanks in advance.
jsonData already contains the parsed response and as you have successfully retrieved success value from it as follows,
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
NSLog(#"%ld",(long)success);
You can retrieve other value as follows,
[[jsonData objectForKey:#"stars"] integerValue]
and so on.
You didn't have to create foundation object by using following method
NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
and following block of code is unnecessary,
for(int i=0;i<_jsonArray.count;i++)
{
NSDictionary * jsonObject = [_jsonArray objectAtIndex:i];
NSString* stars = [jsonObject objectForKey:#"stars"]
NSLog(#"Stars ==> %#", stars);
NSDictionary * jsonObject2 = [_jsonArray objectAtIndex:i];
NSString* followers = [jsonObject2 objectForKey:#"followers"];
NSLog(#"Followers ==> %#", followers);
NSDictionary * jsonObject3 = [_jsonArray objectAtIndex:i];
NSString* photos = [jsonObject3 objectForKey:#"photos"];
NSLog(#"Pictures ==> %#", photos);
}
_jsonArray = [NSJSONSerialization JSONObjectWithData:myNSData options:kNilOptions error:&error];
NSDictionary * jsonObject = (NSDictionary *)_jsonArray;
and then check dictionary object.

Populate the Selected value in Picker view

Here is my Problem. I had a uitableview which had add and edit functionality. At first when I click on Add button it displays a picker view with three components. Component 1 contains list of projects (Select,proj1, proj2, proj3, proj4). I select proj3 and click on submit. Data is able to save in the data base. Now Here comes my problem. The saved data is able to display in the tableview list. When I click on the respective record, it navigates to the detailed edit page where I see proj4 is not selected in the picker view. Instead it is selected as Select following proj1,proj2,proj3 etc,. Here is the code below.
- (void)viewDidLoad
{
[super viewDidLoad];
self.txtstatus.delegate = self;
[self loaddata];
[self loadprojects];
[self loadtasks];
[self loadsubtasks];
[self Benefits];
txthours.enabled = NO;
}
-(void)Benefits
{
NSString *Benefitpost =[[NSString alloc] initWithFormat:#"username=%#",[self.projectpicker dataSource]];
NSString *Benefiturl = #"http://picker.com/GetBenefitTypes";
NSURL *url = [NSURL URLWithString:Benefiturl];
NSData *BenefitpostData = [Benefitpost dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *BenefitpostLength = [NSString stringWithFormat:#"%lu", (unsigned long)[BenefitpostData length]];
NSMutableURLRequest *Benefitrequest = [[NSMutableURLRequest alloc] init];
[Benefitrequest setURL:url];
[Benefitrequest setHTTPMethod:#"POST"];
[Benefitrequest setValue:BenefitpostLength forHTTPHeaderField:#"Content-Length"];
[Benefitrequest setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[Benefitrequest setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[Benefitrequest setHTTPBody:BenefitpostData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *BenefiturlData=[NSURLConnection sendSynchronousRequest:Benefitrequest returningResponse:&response error:&error];
NSURLRequest *BenefiturlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
BenefiturlData = [NSURLConnection sendSynchronousRequest:BenefiturlRequest
returningResponse:&response
error:&error];
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *BenefitresponseData = [NSJSONSerialization JSONObjectWithData:BenefiturlData
options:NSJSONReadingAllowFragments error:&error];
NSArray *Benefitentries = [NSJSONSerialization JSONObjectWithData:[BenefitresponseData dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
if(!Benefitentries)
{
NSLog(#"Error : %#", error);
}
else{
for (NSDictionary *Benefitentry in Benefitentries) {
benID = [Benefitentries valueForKey:#"ID_LEAVES"];
BenefitNames = [Benefitentries valueForKey:#"NM_LEAVES"];
}
NSLog(#"BenefitNames : %#", BenefitNames);
_projectpicker.delegate = self;
_projectpicker.dataSource = self;
[self loadprojects];
}
} else {
}
}
-(void)loadprojects
{
NSString *post =[[NSString alloc] initWithFormat:#"username=%#",[self.projectpicker dataSource]];
//NSString *pickername = [self.projectpicker dataSource];
//NSString *key = #"Da9s^a2Rp4na6R$ikiAsav3Is#niWsa";
//NSString *encrypteduname = [AESCrypt encrypt:pickername password:key];
// Code for Project loading
NSString *projecturltemp = #"http://picker.com/GetAssignedProjects";
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NSString *usrid = str;
NSString * projecturl =[NSString stringWithFormat:#"%#/%#",projecturltemp,usrid];
NSURL *url = [NSURL URLWithString:projecturl];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments error:&error];
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
if(!entries)
{
NSLog(#"Error : %#", error);
}
else{
for (NSDictionary *entry in entries) {
projID = [entries valueForKey:#"ID_PROJECT"];
projectNames = [entries valueForKey:#"NM_PROJECT"];
}
randomSelection=[BenefitNames arrayByAddingObjectsFromArray:projectNames];
randomSelectionID = [benID arrayByAddingObjectsFromArray:projID];
//NSLog(#"Error : %#", projectNames);
//NSLog(#"projID : %#", projID);
_projectpicker.delegate = self;
_projectpicker.dataSource = self;
}
} else {
}
}
-(void)loadtasks
{
// Code for Tasks loading
NSString *post =[[NSString alloc] initWithFormat:#"username=%#",[self.projectpicker dataSource]];
NSString *nsTaskurllocal = #"http://picker.com/GetAssignedTasks/";
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NSString *usrid = str;
NSString * productIdString =[NSString stringWithFormat:#"%#/%#",lblProjects.text,usrid];
//NSLog(#"aString : %#", productIdString);
NSString *aString = [nsTaskurllocal stringByAppendingString:productIdString];
NSURL *nstaskurl = [NSURL URLWithString:aString];
//NSLog(#"nstaskurl : %#", nstaskurl);
NSData *nstaskpostData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *nstaskpostLength = [NSString stringWithFormat:#"%lu", (unsigned long)[nstaskpostData length]];
NSMutableURLRequest *nstaskrequest = [[NSMutableURLRequest alloc] init];
[nstaskrequest setURL:nstaskurl];
[nstaskrequest setHTTPMethod:#"POST"];
[nstaskrequest setValue:nstaskpostLength forHTTPHeaderField:#"Content-Length"];
[nstaskrequest setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[nstaskrequest setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[nstaskrequest setHTTPBody:nstaskpostData];
NSError *nstaskerror = [[NSError alloc] init];
NSHTTPURLResponse *nstaskresponse = nil;
NSData *nstaskurlData=[NSURLConnection sendSynchronousRequest:nstaskrequest returningResponse:&nstaskresponse error:&nstaskerror];
NSURLRequest *nstaskurlRequest = [NSURLRequest requestWithURL:nstaskurl
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
nstaskurlData = [NSURLConnection sendSynchronousRequest:nstaskurlRequest
returningResponse:&nstaskresponse
error:&nstaskerror];
if ([nstaskresponse statusCode] >= 200 && [nstaskresponse statusCode] < 300)
{
NSString *nstaskresponseData = [NSJSONSerialization JSONObjectWithData:nstaskurlData
options:NSJSONReadingAllowFragments error:&nstaskerror];
NSArray *nstaskentries = [NSJSONSerialization JSONObjectWithData:[nstaskresponseData dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&nstaskerror];
if(!nstaskentries)
{
NSLog(#"Error : %#", nstaskerror);
}
else{
for (NSDictionary *nstaskentry in nstaskentries) {
taskID = [nstaskentries valueForKey:#"ID_TASK"];
taskNames = [nstaskentries valueForKey:#"TASk_NAME"];
//NSLog(#"Error : %#", taskNames); //log to see the result in console // by Kiran
}
_projectpicker.delegate = self;
_projectpicker.dataSource = self;
}
} else {
}
}
-(void)loadsubtasks
{
// Code for Sub Tasks loading
NSString *post =[[NSString alloc] initWithFormat:#"username=%#",[self.projectpicker dataSource]];
NSString *nssubTaskurllocal = #"http://picker.com/GetAssignedSubTasks/";
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NSString *usrid = str;
NSString * subproductIdString =[NSString stringWithFormat:#"%#/%#",lblTasks.text,usrid];
//NSLog(#"asubString : %#", subproductIdString);
NSString *aString = [nssubTaskurllocal stringByAppendingString:subproductIdString];
NSURL *nssubtaskurl = [NSURL URLWithString:aString];
//NSLog(#"nsubstaskurl : %#", nssubtaskurl);
NSData *nssubtaskpostData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *nssubtaskpostLength = [NSString stringWithFormat:#"%lu", (unsigned long)[nssubtaskpostData length]];
NSMutableURLRequest *nssubtaskrequest = [[NSMutableURLRequest alloc] init];
[nssubtaskrequest setURL:nssubtaskurl];
[nssubtaskrequest setHTTPMethod:#"POST"];
[nssubtaskrequest setValue:nssubtaskpostLength forHTTPHeaderField:#"Content-Length"];
[nssubtaskrequest setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[nssubtaskrequest setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[nssubtaskrequest setHTTPBody:nssubtaskpostData];
NSError *nssubtaskerror = [[NSError alloc] init];
NSHTTPURLResponse *nssubtaskresponse = nil;
NSData *nssubtaskurlData=[NSURLConnection sendSynchronousRequest:nssubtaskrequest returningResponse:&nssubtaskresponse error:&nssubtaskerror];
NSURLRequest *nssubtaskurlRequest = [NSURLRequest requestWithURL:nssubtaskurl
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
nssubtaskurlData = [NSURLConnection sendSynchronousRequest:nssubtaskurlRequest
returningResponse:&nssubtaskresponse
error:&nssubtaskerror];
if ([nssubtaskresponse statusCode] >= 200 && [nssubtaskresponse statusCode] < 300)
{
NSString *nssubtaskresponseData = [NSJSONSerialization JSONObjectWithData:nssubtaskurlData
options:NSJSONReadingAllowFragments error:&nssubtaskerror];
NSArray *nssubtaskentries = [NSJSONSerialization JSONObjectWithData:[nssubtaskresponseData dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&nssubtaskerror];
if(!nssubtaskentries)
{
NSLog(#"Error : %#", nssubtaskentries);
}
else{
for (NSDictionary *nssubtaskentry in nssubtaskentries) {
subtskID = [nssubtaskentries valueForKey:#"ID_SUB_TASK"];
subtaskNames = [nssubtaskentries valueForKey:#"SUBTASK_NAME"];
//NSLog(#"Error : %#", subtaskNames); //log to see the result in console // by Kiran
}
_projectpicker.delegate = self;
_projectpicker.dataSource = self;
}
} else {
}
}
-(void)loaddata
{
NSString *eventDate = self.projidstocancel;
[[NSUserDefaults standardUserDefaults] setObject:eventDate forKey:#"Eventdate"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSString *post =[[NSString alloc] initWithFormat:#"username=%#",[self.projectpicker dataSource]];
//NSString *pickername = [self.projectpicker dataSource];
//NSString *key = #"Da9s^a2Rp4na6R$ikiAsav3Is#niWsa";
//NSString *encrypteduname = [AESCrypt encrypt:pickername password:key];
// Code for Project loading
NSString *projecturltemp = #"http://picker.com/GetDetailsByID";
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NSString *usrid = str;
NSString * projecturl =[NSString stringWithFormat:#"%#/%#",projecturltemp,self.hdnRowcount];
NSURL *url = [NSURL URLWithString:projecturl];
NSLog(#"projecturl : %#", projecturl);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments error:&error];
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
if(!entries)
{
NSLog(#"Error : %#", error);
}
else{
for (NSDictionary *entry in entries) {
projectNames = [entries valueForKey:#"NM_PROJECT"];
taskNames = [entries valueForKey:#"TASk_NAME"];
subtaskNames = [entries valueForKey:#"SUBTASK_NAME"];
hdnlblProjects.text = [[entries valueForKey:#"NM_PROJECT"]componentsJoinedByString:#""];
hdnlblTasks.text = [[entries valueForKey:#"TASk_NAME"]componentsJoinedByString:#""];
hdnlblSubTasks.text = [[entries valueForKey:#"SUBTASK_NAME"]componentsJoinedByString:#""];
txthours.text = [[entries valueForKey:#"No_Hours"]componentsJoinedByString:#""];
txtstatus.text = [[entries valueForKey:#"STATUS"]componentsJoinedByString:#""];
}
hrsdiff1 = [txthours.text floatValue];
//NSLog(#"taskNames : %#", taskNames);
//NSLog(#"subtask : %#", subtaskNames);
}
} else {
}
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 3;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
int numberofRows = 0;
switch (component) {
case 0:
numberofRows = [randomSelection count];
[pickerView reloadComponent:1];
break;
case 1:
numberofRows = [taskNames count];
[pickerView reloadComponent:2];
break;
case 2:
numberofRows = [subtaskNames count];
break;
}
return numberofRows;
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *title;
if(component == 0) {
[pickerView reloadComponent:1];
[pickerView reloadComponent:2];
title = [randomSelection objectAtIndex:row];
}
else if (component == 1){
[pickerView reloadComponent:2];
title = [taskNames objectAtIndex:row];
}
else{
title = [subtaskNames objectAtIndex:row];
}
return title;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//NSLog(#"%#",myArrayString);
//NSLog(#"%#",myTaskArrayString);
if(component == 0){
NSNumber *myProjectArrayString = [randomSelectionID objectAtIndex:row];
lblProjects.text = [NSString stringWithFormat:#"%#",myProjectArrayString];
lblProjects.hidden = YES;
hdnlblProjects.text = [randomSelection objectAtIndex:[pickerView selectedRowInComponent:0]];
[self loadtasks];
[pickerView reloadComponent:1];
[pickerView reloadComponent:2];
}
//lblProjects.hidden = YES;
else if(component == 1)
{
NSNumber *myTaskArrayString = [taskID objectAtIndex:row];
lblTasks.text = [NSString stringWithFormat:#"%#",myTaskArrayString];
lblTasks.hidden = YES;
hdnlblTasks.text = [taskNames objectAtIndex:[pickerView selectedRowInComponent:1]];
[self loadsubtasks];
[pickerView reloadComponent:2];
}
else if(component == 2)
{
NSNumber *mysubtaskArrayString = [subtskID objectAtIndex:row];
lblSubTasks.text = [NSString stringWithFormat:#"%#",mysubtaskArrayString];
NSLog(#"%#",lblSubTasks.text);
lblSubTasks.hidden = YES;
hdnlblSubTasks.text = [subtaskNames objectAtIndex:[pickerView selectedRowInComponent:2]];
//lblTasks.text = [taskNames objectAtIndex:[pickerView selectedRowInComponent:1]];
//lblTasks.text = [NSString stringWithFormat:#"%#", myTaskArrayString];
//lblSubTasks.text = [subtaskNames objectAtIndex:[pickerView selectedRowInComponent:2]];
}
}

Resources