I have a UICollectionView with thumbnails. When user selects one or multiple images at same time, I have to create NSDictionary with keys and values. Key has to be a specific name. This is the final result I need to get.
(
image[0] = 75829457,
image[1] = 03480923,
image[2] = 58924589
)
Values here are obviously image ids. How can I do that? I need to send that NSDictionary via POST request, which is not a problem.
Any help would be appreciated.
Thank you.
create a method to get ImageDictionary
- (NSDictionary *) dictionaryWithImageArray:(NSArray *)imageArrayID
{
NSMutableDictionary *imageDict = [[NSMutableDictionary alloc] init];
for (int i=0; i<[imageArrayID count]; i++) {
[imageDict setObject:[imageArrayID objectAtIndex:i] forKey:[NSString stringWithFormat:#"image[%d]",i]];
}
return imageDict;
}
Convert that dict to json string
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:<Dict from above>
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *jsonString= nil;
if (! jsonData) {
NSLog(#"Got an error: %#", error);
jsonString = #"";
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
Set Http Body for your request
[request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]];
In your controller, declare a member variable NSMutableString *mutableString. Initialize mutableString in your init method to be empty.
- (void)collectionView:(UICollectionView *)aCollectionView didSelectItemAtIndexPath:(NSIndexPath)indexPath {
NSString *key = [NSString stringWithFormat:#"image[%d]", [indexPath row]];
NSString *value = // get the picture id
NSString *parameter = [NSString stringWithFormat:#"%#=%#", key, value];
if ([mutableString length] != 0)
[mutableString appendString:#"&"];
[mutableString appendString:parameter];
}
Then use an IBAction to confirm the selections, construct your POST request and send it, and then empty the mutable string.
Related
I have a JSON like below (getting from an URL)-
{
action :getAllJournal;
data :{
journalList :[{
cancelled : F;
"cust_code" : "700-T022";
"journal_amount" : 2216;
"journal_code" : "JV1603/001";
"journal_date" : "2016-03-15 00:00:00";
"journal_id" : 1;
outstanding : 0;
},
{
cancelled : F;
"cust_code" : "700-0380";
"journal_amount" : 120;
"journal_code" : "JV1605/006";
"journal_date" : "2016-05-31 00:00:00";
"journal_id" : 2;
outstanding : 120;
},
{
cancelled : F;
"cust_code" : "700-T280";
"journal_amount" : 57;
"journal_code" : "JV1609/001";
"journal_date" : "2016-09-22 00:00:00";
"journal_id" : 3;
outstanding : 0;
}
];
};
message = "";
"message_code" = "";
result = 1;}
The code below doing is getting the JSON from URL and storing them in NSMutableArray. Until storing them into array, it's working fine but I'm bit confused with the JSON format and don't know how to get result by a key.
__block NSMutableArray *jsonArray = nil;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:#"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
{
if (data)
{
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
jsonArray = (NSMutableArray *)myJSON;
NSString *nsstring = [jsonArray description];
NSLog(#"IN STRING -> %#",nsstring);
NSData *data = [nsstring dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if(jsonObject !=nil){
if(![[jsonObject objectForKey:#"journalList"] isEqual:#""]){
NSMutableArray *array=[jsonObject objectForKey:#"journalList"];
NSLog(#"array: %lu",(unsigned long)array.count);
int k = 0;
for(int z = 0; z<array.count;z++){
NSString *strfd = [NSString stringWithFormat:#"%d",k];
NSDictionary *dicr = jsonObject[#"journalList"][strfd];
k=k+1;
// NSLog(#"dicr: %#",dicr);
NSLog(#"cust_code - journal_amount : %# - %#",
[NSMutableString stringWithFormat:#"%#",[dicr objectForKey:#"cust_code"]],
[NSMutableString stringWithFormat:#"%#",[dicr objectForKey:#"journal_amount"]]);
}
}
}else{
NSLog(#"Error - %#",jsonError);
}
}
}];
From this, I am able to get the JSON successfully. But it's always giving me this error: Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in an object around character 6." UserInfo={NSDebugDescription=No string key for value in an object around character 6.} How can I get all values from journalList? I'm new to iOS, that's why not sure what I'm missing.
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
jsonArray = (NSMutableArray *)myJSON;
NSString *nsstring = [jsonArray description];
NSLog(#"IN STRING -> %#",nsstring);
NSData *data = [nsstring dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
I'd say: NO and NO.
I wouldn't do a #try/#catch on a NSJSONSerialization, because the real issues are on the error parameter (and they won't throw a NSException for most of the cases). Just check if (data) is quite efficient.
Then, let's say it worked, and you have myJSON.
In fact, myJSON is a NSDictionary, not a NSArray, so the cast is useless and doesn't make sense.
Next issue:
Your are using -description (okay, if you want to debug), but you CAN'T use it to reconstruct AGAIN a JSON. It's not a valid JSON, it's the way the compiler "print" an object, it adds ";", etc.
If your print [nsstring dataUsingEncoding:NSUTF8StringEncoding] and data you'll see that they aren't the same.
For a more readable:
NSString *dataJSONStr = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];, it's clearly not the same structure as your nsstring.
Then, you are redoing the JSON serialization? Why ?
So:
NSError *errorJSON = nil;
NSDictionary *myJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&errorJSON];
if (errorJSON)
{
NSLog(#"Oops error JSON: %#", errorJSON);
}
NSDictionary *data = myJSON[#"data"];
NSArray *journalList = data[#"journalList"]
for (NSDictionary *aJournalDict in journalList)
{
NSUInteger amount = [aJournalDict[#"journal_amount"] integerValue];
NSString *code = aJournalDict[#"journal_code"];
}
There is a dictionary named "data" you're not fetching, represented by {}.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (!jsonError) {
// Fetch the journalList
NSArray *journalList = json[#"data"][#"journalList"];
// iterate over every entry and output the wanted values
for (NSDictionary *journal in journalList) {
NSLog(#"%# %#", journal[#"cust_code"], journal[#"journal_amount"]);
}
}
json[#"key"] is a short form of [json objectForKey:#"key"] I find easier to read.
That is not a valid JSON. Entries should be separated by comma ,, not semicolon ;
You need to fetch journalList from data.
Try below code:
This is demo code to create array like you:
NSMutableDictionary *jsonObject = [NSMutableDictionary new];
jsonObject[#"action"]= #"";
jsonObject[#"message"]= #"";
jsonObject[#"message_code"]= #"";
jsonObject[#"result"]= #"1";
NSMutableArray *ary1 = [NSMutableArray new];
for(int i=0;i<5;i++)
{
NSMutableDictionary *dd = [NSMutableDictionary new];
dd[#"cancelled"]= #"F";
dd[#"cust_code"]= #"F";
[ary1 addObject:dd];
}
NSMutableDictionary *dicjournal = [NSMutableDictionary new];
[dicjournal setObject:ary1 forKey:#"journalList"];
[jsonObject setObject:dicjournal forKey:#"data"];
This is main Logic:
NSMutableArray *journalList = [NSMutableArray new];
NSMutableDictionary *dic = [jsonObject valueForKey:#"data"];
journalList = [[dic objectForKey:#"journalList"] mutableCopy];
Looks like your JSON is invalid. You can see whether your JSON is correct or not using http://jsonviewer.stack.hu/ and moreover format it. Meanwhile your code is not using "data" key to fetch "journalList" array.
Code : -
NSDictionary *dic = [jsonObject valueForKey:#"data"];
NSMutableArray *arr = [dic objectForKey:#"journalList"];
for (int index=0 ; index < arr.count ; index++){
NSDictionary *obj = [arr objectAtIndex:index];
// Now use object for key from this obj to get particular key
}
Thanks #Larme and #Amset for the help. I was doing wrong the in the NSMutableArray part. The correct version of this code is in the below:
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:#"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
{
if (data)
{
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
NSArray *journalList = myJSON[#"data"][#"journalList"];
for (NSDictionary *journal in journalList) {
NSLog(#"%# %#", journal[#"journal_date"], journal[#"journal_amount"]);
}
}
}];
I am trying to make a nsurl request and manage to retrieve the web response data out. The problem is i want to retrieve the specific parameter from the JSON list. The parameter i want to retrieve is "id" and display it out in a label.
Here is my viewDIDLoad for establishing the connection:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
feeds = [[NSMutableArray alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://coolsoft.mousy.com/v1/messi/reports"]];
// Prepare the variables for the JSON response
// Create a mutable copy of the immutable request and add more headers
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[mutableRequest addValue:#"application/json" forHTTPHeaderField:#"request"];
// Make synchronous request
request = [mutableRequest copy];
// Log the output to make sure our new headers are there
NSLog(#"%#", request.allHTTPHeaderFields);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
if(connection)
{
_webResponseData = [NSMutableData data] ;
}
else
{
NSLog(#"Connection is NULL");
}
}
His is my connectionDidFinishLoading method:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Received %lu Bytes", (unsigned long)[_webResponseData length]);
// NSString *theXML = [[NSString alloc] initWithBytes:
// [_webResponseData mutableBytes] length:[_webResponseData length] encoding:NSUTF8StringEncoding];
// convert to JSON
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.webResponseData options:NSJSONReadingMutableLeaves error:&myError];
NSString *icon;
// show all values
for(id key in res) {
id value = [res objectForKey:key];
NSString *keyAsString = (NSString *)key;
NSString *valueAsString = (NSString *)value;
NSLog(#"key: %#", keyAsString);
NSLog(#"value: %#", valueAsString);
}
// extract specific value...
NSArray *results = [res objectForKey:#"id"];
for (NSDictionary *result in results) {
icon = [result objectForKey:#"id"];
NSLog(#"icon: %#", icon);
}
output.text = icon;
output = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 100)]; //adjust label size and position as needed
output.font = [UIFont fontWithName:#"BradleyHandITCTT-Bold" size: 23.0];
output.textColor = [UIColor whiteColor];
output.textAlignment = NSTextAlignmentCenter;
output.numberOfLines = 0; //note: I said number of lines need to be 2
output.backgroundColor = [UIColor clearColor];
output.adjustsFontSizeToFitWidth = YES;
output.tag = 100;
}
Here is output when i NSLOG the res dictionary:
( { date = "2014-08-28T00:00:00Z"; id = 300005; title = "July 2014 USAA Phishing Campaign Uses KeNiHaCk Exploit"; uri = "/v1/joker/reports/300005"; }, { date = "2014-12-16T20:46:29Z"; id = 300062; title = "Two-Year Chinese Spearphishing Campaign Largely Targeted Japanese Aerospace and Energy Industries"; uri = "/v1/joker/reports/300062"; },
Here is my error message:
-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x136713360
2015-12-30 11:58:17.692 FYP_IOS_APP[817:323807] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x136713360'
Your JSON response is {"id":300005,"title":"pink","date":"2014-08-28T00:00:00Z","uri":"www.hipster.com/hip"}}
So, You can use like, lblName.text = [res valueForKey:#"id"];
Your json parsing is OK and it gives you JSON to NSDictionary
but you need some minor changes in pasing that NSDictionary object as below.
see this below code & It may help you
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
//{"id":300005, "title":"pink", "date":"2014-08-28T00:00:00Z", "uri":"www.hipster.com/hip"}
NSLog(#"Received %lu Bytes", (unsigned long)[_webResponseData length]);
// convert to JSON
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.webResponseData options:NSJSONReadingMutableLeaves error:&myError];
NSString *icon;
// show all values
for(id key in [res allKeys]) {
NSLog(#"key: %#", key);
NSLog(#"value: %#", [res objectForKey:key]);
}
// extract specific value...
icon = [res valueForKey:#"id"];
NSLog(#"icon: %#", icon);
output.text = icon;
output = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 100)]; //adjust label size and position as needed
output.font = [UIFont fontWithName:#"BradleyHandITCTT-Bold" size: 23.0];
output.textColor = [UIColor whiteColor];
output.textAlignment = NSTextAlignmentCenter;
output.numberOfLines = 0; //note: I said number of lines need to be 2
output.backgroundColor = [UIColor clearColor];
output.adjustsFontSizeToFitWidth = YES;
output.tag = 100;
}
update
// convert to JSON
NSError *myError = nil;
NSArray *res = [NSJSONSerialization JSONObjectWithData:self.webResponseData options:NSJSONReadingMutableLeaves error:&myError];
// show all values
for(NSDictionary *dic in res) {
for(NSString *key in [dic allKeys]) {
NSLog(#"key: %#", key);
NSLog(#"value: %#", [dic objectForKey:key]);
}
}
I want to create a JSON like this
[{"phone":"3456345"}, {"phone":"2423242"}, {"phone":"2423423"}]
I have an array in which i have phone numbers only. Below code will create the JSON but for that i need to create dictionary first.
contactData =[NSJSONSerialization dataWithJSONObject:contacts options:NSJSONWritingPrettyPrinted error:&error];
I have tried to create Dictionary like this but it only enter last value because i can't have duplicate value for one key. please tell me how do i solve the problem?
int i=0;
for (i=0; i<[all_contacts count]; i++)
{
[contacts setObject:[all_contacts objectAtIndex:i] forKey:#"phone"];
}
How can i create the json here.Please tell?
Assuming all_contacts looks like this:
[ "3456345", "2423242", "2423423" ]
Then this should work:
NSMutableArray *root = [NSMutableArray new];
for (NSString *number in all_contacts) {
[root addObject:#{ "phone": number }];
}
contactData =[NSJSONSerialization dataWithJSONObject:root
options:NSJSONWritingPrettyPrinted
error:&error];
int i=0;
NSMutableArray *contacts = [[NSMutableArray alloc] init];
for (i=0; i<[all_contacts count]; i++) {
[contacts addObject:#{#"phone" : [all_contacts objectAtIndex:i]}];
}
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:contacts options:0 error:&error];
if (!jsonData) {
//error here
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
In my app, I am parsing the data using JSON
NSString * urlString=[NSString stringWithFormat:#"http://userRequest?userid=bala#gmail.com&latitude=59.34324&longitude=23.359257"];
NSURL * url=[NSURL URLWithString:urlString];
NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:url];
NSError * error;
NSURLResponse * response;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * outputData=[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",outputData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:outputData error:nil];
NSLog(#"%#",jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
After this code executes, In my log it is printed as
({
latitude = "0.000000000000000";
longitude = "0.000000000000000";
username = sunil;
},
{
latitude = "80.000000000000000";
longitude = "30.000000000000000";
username = arun;
})
But while running, the app crashes, as
'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x910d8d0'
I think your problem is, that jsonParser objectWithString returns an array with dictionaries in it not dictionaries itself.
Try the following:
NSArray *jsonData = (NSArray *) [jsonParser objectWithString:outputData error:nil];
for(NSDictionary *dict in jsonData) {
NSLog(#"%#",dict);
}
Does that work for you ?
Your reponse is NSArray which contains NSDictionary. So frst get dictionary from array then access value. Also Your json not look like correct.
for (NSDictionary *dict in responseArray) {
double latitude = [dict[#"latitude"]doubleValue];
double longitude = [dict[#"latitude"] longitude];
NSString* name = dict[#"username"];
}
1. First of all you are getting NSArray in JSON
JSON Starts with "(" means NSArray
JSON Starts with "{" means NSDictionary
Here you are getting NSArray which has collection of NSDictionary,
{
latitude = "0.000000000000000";
longitude = "0.000000000000000";
username = sunil;
},...
2."success" key is not present in the JSON..
Fix
NSArray *jsonData = (NSArray *) [jsonParser objectWithString:outputData error:nil];
If([jsonData count]>0){
// Has some data
// Iterate NSDictionary and get data here
}
else{
// No Data
}
some where you are getting data from nsarray with using some object key. that key is invalid to fetching data from array
{"response":[33689822,64091979,69682048,74160161]}
-
- (void)requestCompleted:(ASIHTTPRequest *)request
{
NSString *responseString = [request responseString];
NSLog(#"okRequest|| %#",responseString);
SBJSON *parser = [[SBJSON alloc] init];
// Prepare URL request to download statuses from Twitter
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithString:responseString];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
//all other func..
NSLog(#"%# ", status);///This func prints only "response"
}
}
How I can get array of numbers in "response"? (33689822,64091979,69682048,74160161)
Try this:
for (NSNumber *number in [statuses objectForKey:#"response"]) {
NSLog(#"%#", number);
}
You can either parse the JSON data yourself, or better, use a library like TouchJSON to do it for you.
Try using JSONFragmentValue directly.
NSString *response=[request responseString];
id usableResp = [response JSONFragmentValue];