In my project i have an array which contains multiple dictionaries with some key values each. I want to get the all the value of "Link" key into an NSMutableArray.
the current array which contain dictionary is in the form of:
(
{
YoutubeVideo = {
description = "Cervical Spine Medial Branch Nerve Neurolysis neurosurgical animations";
link = "https://player.vimeo.com/video/26186155";
title = "Cervical Spine Medial Branch Nerve Neurolysis neurosurgical animations";
};
},
{
YoutubeVideo = {
description = "What is endoscopic brain surgery";
link = "https://player.vimeo.com/video/16144037";
title = "What is endoscopic brain surgery";
};
},
{
YoutubeVideo = {
description = "Cervical Spine Medial Branch Nerve Block Injection pain management";
link = "https://player.vimeo.com/video/26186167";
title = "Cervical Spine Medial Branch Nerve Block Injection pain management";
};
},
{
YoutubeVideo = {
description = "Seguiremos - Hospital Sant Joan de D\U00e9u y Macaco";
link = "https://player.vimeo.com/video/54275902";
title = "Seguiremos - Hospital Sant Joan de D\U00e9u y Macaco";
};
},
{
YoutubeVideo = {
description = "Basic Shoulder Arthroscopy in Orthopaedics";
link = "https://www.youtube.com/embed/ywBVWIzGxtw";
title = "Basic Shoulder Arthroscopy in Orthopaedics";
};
}
i want to get all the values of link into a single array.
Currently the code i use which gives the following output is:
-(void)videolisting
{
NSString *post = #"api_key=bf45c093e542f057c123ae7d6";
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://hChe/api/video"]];
[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);
vidnamearray = [dict6 objectForKey:#"video"];
NSLog(#" Required Dir: %#",vidnamearray);
}
Try below solution
NSMutableArray *subArray=[[NSMutableArray alloc]init];
for(NSDictionary *dict in vidnamearray)
{
NSDictionary *subDict=[dict valueForKey:#"YoutubeVideo"];
[subArray addObject:[subDict valueForKey:#"link"]];
}
subArray will get all the values in the link key..!
Hope it helps you.....!
Try this
yourArr.valueForKeyPath("YoutubeVideo.link")
This will give the array containing all links.
Related
In my project I am showing the values of NSMutableDictionary on a UITableview. It works fine. On my UITableView I also have an Edit button. The only thing I want is that when I click on edit button the whole data will show on the next view.
The values which have to shown on edit view will get on the basis of Key- 'id'.
Please help me to how to get the value of Key- 'id'. and use it on the second view to display details.
I am using the following code:
-(void)physiciandata
{
NSString *post = [NSString stringWithFormat:#"data[Users][ref_id]=%#&api_key=bf45c093e542f057c123ae7d6",refidstr];
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://192.168.0.20/hsch/api/user_procedure_list"]];
[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];
[request setHTTPBody:postData];
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
//NSLog(#"str : %#",dict6);
physiciandict = [[[dict6 objectForKey:#"procedure"] objectAtIndex:0] objectForKey:#"PhysiciansProcedures"];
physiciandict1 = [[[dict6 objectForKey:#"procedure"] objectAtIndex:0] objectForKey:#"Procedures"];
//diagnosedictforname = [[[dict6 objectForKey:#"diagnoses"]objectAtIndex:0]objectForKey:#"Diagnoses"];
NSLog(#" for ref id =%# , data is= %# , and %# " ,refidstr, physiciandict , physiciandict1);
CompletephyDic = [physiciandict mutableCopy];
[CompletephyDic addEntriesFromDictionary:physiciandict1];
NSLog(#"Complete data is %#",CompletephyDic);
}
and this is the code I put to display data on tableView
{
NSString *strid = [physiciandict objectForKey:#"id"];
serialnmbrphysician.text = #"";
serialnmbrphysician.text = strid;
serialnmbrphysician.backgroundColor = [UIColor lightGrayColor];
NSLog(#"data1 %#",strid);
NSString * strName= [CompletephyDic objectForKey:#"procedure_name"];
procedurename.text = #"";
procedurename.text = strName;
procedurename.backgroundColor = [UIColor lightGrayColor];
NSLog(#"data2 %#",strName);
NSString *strName2 = [CompletephyDic objectForKey:#"procedure_code"];
procedurecode.text = #"";
procedurecode.text = strName2;
procedurecode.backgroundColor = [UIColor lightGrayColor];
NSLog(#"data3 %#",strName2);
NSString *strName3 = [physiciandict objectForKey:#"charge_amt"];
averagemedicareallowedamount.text = #"";
averagemedicareallowedamount.text = strName3;
averagemedicareallowedamount.backgroundColor = [UIColor lightGrayColor];
NSLog(#"data4 %#",strName3);
NSString *strName4 = [physiciandict objectForKey:#"total_amt"];
avgsubmittedchargeamount.text = #"";
avgsubmittedchargeamount.text = strName4;
avgsubmittedchargeamount.backgroundColor = [UIColor lightGrayColor];
NSLog(#"data5 %#",strName4);
NSString *strName5 = [physiciandict objectForKey:#"medicare_amt"];
avgmedicarepaymentamount.text = #"";
avgmedicarepaymentamount.text = strName5;
avgmedicarepaymentamount.backgroundColor = [UIColor lightGrayColor];
NSLog(#"data6 %#",strName5);
}
in my project i am using JSON parsing to display data for this i created 2 NSDictionary dictionary 1 return success response but when i call it in second dictionary it return Null value.
i am sharing my code please help me to correct it
-(void)hdata
{
NSString *post = [NSString stringWithFormat:#"data[Users][ref_id]=%#&api_key=bf45c093e542f057c123ae7d6",refidstr];
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://192.168.0.20/hspCh/api/user_diagnose_list"]];
[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];
[request setHTTPBody:postData];
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6); <=======it gives correct responce
diagnosisdict = [dict6 objectForKey:#"data[Users][ref_id]"];
[diagnosisdict setValue:refidstr forKey:#"data[Users][ref_id]"];
NSLog(#" for ref id =%# , data is= %#",refidstr, diagnosisdict); <======Gives null responce
}
Output of the above in console is as follows
2015-12-09 10:34:16.935 HcH[2841:32315] str : {"response":200,"diagnoses":[{"DiagnosesHospitals":{"hospital_id":"3341","id":"163075","discharges":"100.00","charge_amt":"1200.00","total_amt":"1500.00","medicare_amt":"1200.00"},"Diagnoses":{"diagnosis_name":"TRANSIENT ISCHEMIA"}}]}
2015-12-09 10:34:16.935 HcH[2841:32315] str : {
diagnoses = (
{
Diagnoses = {
"diagnosis_name" = "TRANSIENT ISCHEMIA";
};
DiagnosesHospitals = {
"charge_amt" = "1200.00";
discharges = "100.00";
"hospital_id" = 3341;
id = 163075;
"medicare_amt" = "1200.00";
"total_amt" = "1500.00";
};
}
);
response = 200;
}
2015-12-09 10:34:16.936 HcH[2841:32315] for ref id =3341 , data is= (null)
Replace this
diagnosisdict = [dict6 objectForKey:#"data[Users][ref_id]"];
with
diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
There is no entry in dict6 for "data[Users][ref_id]".
Using that string as a key is completely nonsensical, by the way. A key in this context is just a string, not a series of accesses in dictionaries.
It seems like what you want is dict6[#"data"][#"Users"][#"ref_id"].
However, this will also fail, because there is no entry for "data" in dict6.
It is possible that your cleanJSONToObject: method is stripping out the value of the "data" key. However, based on your statement that printing the value of dict6 gives the correct response, I assume that what you actually want to access is the value of "id" in "DiagnosesHospitals", since it sounds the most like a "ref_id".
Based on the output of the debugger, it seems as though you have a dictionary (dict6) with a "diagnoses" key pointing to an array with two dictionaries.
So, You would access the "id" field with dict6[diagnoses][0][#"DiagnosesHospitals"][#"id"], assuming that "id" is a string (I'm not sure why it has no quotes around it).
Somethings that you can get:
NSDictionary * diagnoses = dict6[#"diagnoses"];
NSString * diagnosis_name = diagnoses[0][#"Diagnoses"][#"diagnosis_name"];
NSDictionary * diagnosisdict = diagnoses[0][#"DiagnosesHospitals"];
NSString * hospital_id = diagnosisdict[#"hospital_id"];
I have created a small project that can read and insert data from iPhone to sql server via RESTful WCF service.
I have read the data successfully with the following approach:
1- I have created a wcf web service that read data from Sql serverwith table Employees(firstname,lastname,salary):
"41.142.251.142/JsonWcfService/GetEmployees.svc/json/employees"
2- I have created a new project in xcode 5.0.2, and I added a textfield (viewData.text) to display data retrieved by the web service.
3- I added the following instruction in my viewController.m :
"#define WcfSeviceURL [NSURL URLWithString: #"41.142.251.142/JsonWcfService/GetEmployees.svc/json/employees"]"
3- In (void)viewDidLoad method, I implemented the below code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:WcfSeviceURL options:NSDataReadingUncached error:&error];
if(!error)
{
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
NSMutableArray *array= [json objectForKey:#"GetAllEmployeesMethodResult"];
for(int i=0; i< array.count; i++)
{
NSDictionary *empInfo= [array objectAtIndex:i];
NSString *first = [empInfo objectForKey:#"firstname"];
NSString *last = [empInfo objectForKey:#"lastname"];
NSString *salary = [empInfo objectForKey:#"salary"];
//Take out whitespaces from String
NSString *firstname = [first
stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *lastname = [last
stringByReplacingOccurrencesOfString:#" " withString:#""];
viewData.text= [viewData.text stringByAppendingString:[NSString stringWithFormat:#"%# %# makes $%#.00 per year.\n",firstname,lastname,salary]];
}
}
}
Check the following link : http://www.codeproject.com/Articles/405189/How-to-access-SQL-database-from-an-iPhone-app-Via.
As I mentioned, I can read the data from my iPhone without any problem.
So the second step is how to write and insert data from the iPhone to sql server.
for this, I created first the method that insert data in my webservice:
In WCF interface:
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "json/InsertEmployee/{id1}/{id2}/{id3}")]
bool InsertEmployeeMethod(string id1,string id2, string id3);
In Implementation:
public bool InsertEmployeeMethod(string id1,string id2, string id3)
{
int success = 0;
using (SqlConnection conn = new SqlConnection("server=(local);database=EmpDB;Integrated Security=SSPI;"))
{
conn.Open();
decimal value= Decimal.Parse(id3);
string cmdStr = string.Format("INSERT INTO EmpInfo VALUES('{0}','{1}',{2})",id1,id2,value);
SqlCommand cmd = new SqlCommand(cmdStr, conn);
success = cmd.ExecuteNonQuery();
conn.Close();
}
return (success != 0 ? true : false);
}
So to test this web servcie method use:
"41.142.251.142/JsonWcfService/GetEmployees.svc/json/InsertEmployee/myName/MylastName/6565"
Then to consume this method from iPhone I used the following approach:
I decalared the Define Instruction:
"#define BaseWcfUrl [NSURL URLWithString:
#"41.142.251.142/JsonWcfService/GetEmployees.svc/json/InsertEmployee/{id1}/{id2}/{id3}"]"
Then I implemented the Insert Employee Method related to click button.
-(void) insertEmployeeMethod
{
if(firstname.text.length && lastname.text.length && salary.text.length)
{
NSString *str = [BaseWcfUrl stringByAppendingFormat:#"InsertEmployee/%#/%#/%#",firstname.text,lastname.text,salary.text];
NSURL *WcfServiceURL = [NSURL URLWithString:str];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:WcfServiceURL];
[request setHTTPMethod:#"POST"];
// connect to the web
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *respStr = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:respData
options:NSJSONReadingMutableContainers
error:&error];
NSNumber *isSuccessNumber = (NSNumber*)[json objectForKey:#"InsertEmployeeMethodResult"];
//create some label field to display status
status.text = (isSuccessNumber && [isSuccessNumber boolValue] == YES) ? [NSString stringWithFormat:#"Inserted %#, %#",firstname.text,lastname.text]:[NSString stringWithFormat:#"Failed to insert %#, %#",firstname.text,lastname.text];
}
}
But the issue here, is in the following instruction:
NSString *str = [BaseWcfUrl stringByAppendingFormat:#"InsertEmployee/%#/%#/%#",firstname.text,lastname.text,salary.text];
Always the system returns a message 'Data parameter nil' with this line, knowing that the firstname.text, and lastname.text, salary are all filled and I can see their values with NSLog(#"First Name :%#",firstname.text)...
Can you please help on this?
Thanks in advance.
I don't think NSURLs stringByAppendingFormat will do what you want.
Try something like this:
#define kBase_URL #"41.142.251.142/JsonWcfService/GetEmployees.svc/json/%#"
#define kAuthAPI_InsertEmployee_URL [NSString stringWithFormat:kBase_URL, #"InsertEmployee/%#/%#/%#"]
//Setup session
NSError *error;
NSURL *requestURL = [NSURL URLWithString:[NSString stringWithFormat:kAuthAPI_InsertEmployee_URL,firstname.text,lastname.text,salary.text]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:profileData options:0 error:&error];
[request setHTTPBody:postData];
etc. etc.
I get an self.usersArray with 2 elements in the format:
(
{
userCreated = "2012-01-05 12:27:22";
username = Simulator;
},
{
userCreated = "2013-01-01 14:27:22";
username = "joey ";
}
)
This is gotten in a completion block after which I call another method to fetch points for these 2 users through a helper class:
-(void)getPoints{
self.usersPointsArray = [[NSMutableArray alloc] init];
for (NSDictionary *usersDictionary in self.usersArray) {
[SantiappsHelper fetchPointsForUser:[usersDictionary objectForKey:#"username"] WithCompletionHandler:^(NSArray *points){
if ([points count] > 0) {
[self.usersPointsArray addObject:[points objectAtIndex:0]];
}
NSLog(#"self.usersPointsArray %#", self.usersPointsArray);
}];
}
}
The final self.usersPointsArray log looks like:
(
{
PUNTOS = 5;
username = Simulator;
},
{
PUNTOS = 2;
username = joey;
}
)
But the problem is that the way the call for points is structured, the self.usersPointsArray is returned twice, each time with an additional object, due to the for loop, I know.
Here is the Helper class method:
+(void)fetchPointsForUser:(NSString*)usuario WithCompletionHandler:(Handler2)handler{
NSURL *url = [NSURL URLWithString:#"http://myserver.com/myapp/readpoints.php"];
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:usuario, #"userNa", nil];
NSData *postData = [self encodeDictionary:postDict];
// Create the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
__block NSArray *pointsArray = [[NSArray alloc] init];
dispatch_async(dispatch_get_main_queue(), ^{
// Peform the request
NSURLResponse *response;
NSError *error = nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (error) {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSLog(#"HTTP Error: %d %#", httpResponse.statusCode, error);
return;
}
return;
}
NSString *responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
pointsArray = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSASCIIStringEncoding] options:0 error:nil];
if (handler)
handler(pointsArray);
});
}
I cannot use the self.usersPointsArray with the initial objects, only with the finalized object. It wont always be 2 elements, i actually dont know how many it will be.
What would be the way to structure it so I get a final call when the self.usersPointsArray is complete and then I reload my tableview?
I think of your problem as a standard consumer-producer problem. You can create a queue count for the amount of items that will be processed (int totalToProcess=self.usersArray.count). Each time the completion handler is hit, it will do totalToProcess--. When totalToProcess reaches 0 you have processed all of the elements in your queue and can refresh your table.
If I understand your question correctly I believe this solves your problem. If not, hopefully I can with a bit more information.
I am using Parse.com as a backend of my application, where I am currently storing the data there.
The data is a list of video game consoles. I was able to make an output of it, but instead of JSON data, the output is a big NSMutableArray.
This is my viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:#"https://api.parse.com/1/classes/Consoles"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"APPLICATION_ID" forHTTPHeaderField:#"X-Parse-Application-Id"];
[request setValue:#"REST_API_KEY" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
NSError *error;
id listOfConsoles = [NSJSONSerialization JSONObjectWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] options:NSJSONReadingMutableContainers error:&error];
NSLog(#"The list: %#", listOfConsoles);
}
The output:
The list: {
results = (
{
createdAt = "2013-03-21T07:26:04.149Z";
name = PlayStation;
objectId = vloIK0MZIA;
updatedAt = "2013-03-21T07:26:04.149Z";
},
{
createdAt = "2013-03-21T07:26:34.209Z";
name = Wii;
objectId = RIRpgbznlq;
updatedAt = "2013-03-21T07:26:34.209Z";
},
{
createdAt = "2013-03-21T07:26:39.391Z";
name = Xbox;
objectId = xBNgHtJbrV;
updatedAt = "2013-03-21T07:26:39.391Z";
}
);
}
What I want the output to be:
{
"results" : [
{
"objectId" : "vloIK0MZIA",
"updatedAt" : "2013-03-21T07:26:04.149Z",
"createdAt" : "2013-03-21T07:26:04.149Z",
"name" : "PlayStation"
},
{
"objectId" : "RIRpgbznlq",
"updatedAt" : "2013-03-21T07:26:34.209Z",
"createdAt" : "2013-03-21T07:26:34.209Z",
"name" : "Wii"
},
{
"objectId" : "xBNgHtJbrV",
"updatedAt" : "2013-03-21T07:26:39.391Z",
"createdAt" : "2013-03-21T07:26:39.391Z",
"name" : "Xbox"
}
]
}
BY THE WAY
Why is it that when I have a separate NSData in the code:
NSData *JSONData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
And change my NSJSONSerialization to:
id listOfConsoles = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&error];
The output will be:
The list: {
error = unauthorized;
}
The first list is a NSDictionary with a single key called "results" which has an NSArray of NSDictionaries.
The second list is the same thing..
Edit 1.0:
Just to clarify, the second output is JSON, ok? Simply as that, just check here and validate yourself. The first one is the outputted JSON that is inside an NSObject. Of course there will be slight differences...
Your Authentication not done successfully. Please check APPLICATION_ID and REST_API_KEY values.
I was an idiot. I never realized that I tried to convert the JSON to something else, when I wanted the JSON data.
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:#"https://api.parse.com/1/classes/Consoles"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"APPLICATION_ID" forHTTPHeaderField:#"X-Parse-Application-Id"];
[request setValue:#"REST_API_KEY" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
NSString *listOfConsoles = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
NSLog(#"%#", listOfConsoles);
}