How to add GET parameters to an ASIHttpRequest? - iphone

How can I add GET parameters to an ASIHttpRequest?
I want to go from http://mysite.com/server to http://mysite.com/server?a=1&b=2 programmatically.
I have all my parameters as key-value pairs in an NSDictionary object.
Thanks

Use string format like
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:#"1",#"a",#"2",#"b", nil];
NSMutableString *prams = [[NSMutableString alloc] init];
for (id keys in dict) {
[prams appendFormat:#"%#=%#&",keys,[dict objectForKey:keys]];
}
NSString *removeLastChar = [prams substringWithRange:NSMakeRange(0, [prams length]-1)];
NSString *urlString = [NSString stringWithFormat:#"http://mysite.com/server?%#",removeLastChar];
NSLog(#"urlString %#",urlString);

Related

Convert NSString to NSDictionary separated by specific character

I need to convert this "5?8?519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21" string into dictionary. Separated by "?"
Dictionary would be some thing like
{
sometext1 = "5",
sometext2 = "8",
sometext3 = "519223cef9cee4df999436c5e8f3e96a",
sometext4 = "EVAL_TIME",
sometext5 = "60",
sometext6 = "2013-03-21"
}
Thank you .
Break the string to smaller strings and loop for them.
This is the way
NSArray *objects = [inputString componentsSeparatedByString:#"?"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
int i = 1;
for (NSString *str in objects)
{
[dict setObject:str forKey:[NSString stringWithFormat:#"sometext%d", i++]];
}
Try
NSString *string = #"5?8?3519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21";
NSArray *stringComponents = [string componentsSeparatedByString:#"?"];
//This is very risky, your code is at the mercy of the input string
NSArray *keys = #[#"cid",#"avid",#"sid",#"TLicense",#"LLicense",#"date"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
for (int idx = 0; idx<[stringComponents count]; idx++) {
NSString *value = stringComponents[idx];
NSString *key = keys[idx];
[dictionary setObject:value forKey:key];
}
EDIT: More optimized
NSString *string = #"5?8?3519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21";
NSArray *stringComponents = [string componentsSeparatedByString:#"?"];
NSArray *keys = #[#"cid",#"avid",#"sid",#"TLicense",#"LLicense",#"date"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjects:stringComponents forKeys:keys];
first separate the string into several arrays by '?'.
then add the string in you dictionary.
sth like this:
NSString *str = #"5?8?519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21";
NSArray *valueArray = [str componentsSeparatedByString:#"?"];
NSMutableArray *keyArray = [[NSMutableArray alloc] init];
for (int i = 0; i <[valueArray count]; i ++) {
[keyArray addObject:[NSString stringWithFormat:#"sometext%d",i+1]];
}
NSDictionary *dic = [[NSDictionary alloc] initWithObjects:valueArray forKeys:keyArray];
For the future: If you were to store your data in JSON format (closer to what you have anyway), it'll be much easier to deal with and transfer between systems. You can easily read it...using NSJSONSerialization

Getting crashed when NSdictionary or NSString values into UILABEL

-(void) httpDataDidFinishLoadingWithData:(NSData *)theData
{
m_activityLoaded=NO;
temp=[[NSString alloc] initWithData:[dataLoader httpData]
encoding:NSUTF8StringEncoding];
NSLog(#"TEMP IS TEMP %#", temp);
NSDictionary *dict = [[NSDictionary alloc]init];
dict = [[temp JSONValue] objectForKey:#"location"];
NSDictionary *dict1 = [[NSDictionary alloc]init];
dict1 = [[temp JSONValue] objectForKey:#"wind"];
NSDictionary *dict2 = [[NSDictionary alloc]init];
dict2 = [dict1 objectForKey:#"direction"];
NSDictionary *dict3 = [[NSDictionary alloc]init];
dict3 = [[temp JSONValue] objectForKey:#"atmosphere"];
NSDictionary *dict4 = [[NSDictionary alloc]init];
dict4 = [[temp JSONValue] objectForKey:#"condition"];
NSDictionary *dict5 = [[NSDictionary alloc]init];
dict5 = [dict4 objectForKey:#"text"];
NSDictionary *dict6 = [[NSDictionary alloc]init];
dict6 = [dict4 objectForKey:#"code"];
NSDictionary *dict7 = [[NSDictionary alloc]init];
dict7 = [dict4 objectForKey:#"temperature"];
temperatureLabel.text = [dict4 objectForKey:#"temperature"];
}
Crash occurs at temperatureLabel.text = [dict4 objectForKey:#"temperature"];
I dont know man, Data is exactly printed in the console, but crashing at UILABEL(temperatureLabel). Help me out, thanks in advance
if you look at the error you are getting it is telling you that the object return for the key temperature is not a NSString or NSDictionary but a NSNumber.
Give this a try:
-(void) httpDataDidFinishLoadingWithData:(NSData *)theData {
m_activityLoaded=NO;
temp=[[NSString alloc] initWithData:[dataLoader httpData]
encoding:NSUTF8StringEncoding];
NSLog(#"TEMP IS TEMP %#", temp);
NSDictionary *dict = [[temp JSONValue] objectForKey:#"location"];
NSDictionary *dict1 = [[temp JSONValue] objectForKey:#"wind"];
NSDictionary *dict2 = [dict1 objectForKey:#"direction"];
NSDictionary *dict3 = [[temp JSONValue] objectForKey:#"atmosphere"];
NSDictionary *dict4 = [[temp JSONValue] objectForKey:#"condition"];
NSDictionary *dict5 = [dict4 objectForKey:#"text"];
NSDictionary *dict6 = [dict4 objectForKey:#"code"];
NSNumber *temperature = [dict4 objectForKey:#"temperature"];
temperatureLabel.text = [NSString stringWithFormat:#"%#", temperature];
}
You might want to look at NSNumberFormatter for formatter the temperature with something like: °F or °C.
Are you sure that your object is of NSString class?
Try putting in something like:
if([[dict4 objectForKey:#"temperature"] isKindOfClass:[NSString class]])
NSLog(#"lalala");
If it does not get logged to the console it means that your object is not an NSString and you could try something like:
temperatureLabel.text = [NSString stringWithFormat:#"%#", [dict4 objectForKey:#"temperature"]];
You should change the %# according to the kind of object you have stored in your dictionnary.
Your dictionary contains an NSNumber instance and you are assigning that to a property of type NSString. The crash message is your tip off there. Use stringValue or some other way to get the number's data into string form.

Using SBJson, how to retrieve list of strings from array of objects? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Parse JSON in Objective-C with SBJSON
I have below JSON Response (String). I want to parse it into an NSArray with all the patient names.
[{"pat_reg_no":"111181031P1","app_start_time":"10.15","pat_firstname":"Will Smith"},
{"pat_reg_no":"111181031P2","app_start_time":"11.15","pat_firstname":"Shane Watson"},
{"pat_reg_no":"111181031P3","app_start_time":"12.15","pat_firstname":"Michael Hussey"},
{"pat_reg_no":"111181031P1","app_start_time":"10.15","pat_firstname":"Will Smith"}]
How do I parse this?
I write a demo for you.
SBJsonParser *parser = [[SBJsonParser alloc] init];
id jsonObj = [parser objectWithString:#"[{\"pat_reg_no\":\"111181031P1\",\"app_start_time\":\"10.15\",\"pat_firstname\":\"Will Smith\"},{\"pat_reg_no\":\"111181031P2\",\"app_start_time\":\"11.15\",\"pat_firstname\":\"Shane Watson\"},{\"pat_reg_no\":\"111181031P3\",\"app_start_time\":\"12.15\",\"pat_firstname\":\"Michael Hussey\"},{\"pat_reg_no\":\"111181031P1\",\"app_start_time\":\"10.15\",\"pat_firstname\":\"Will Smith\"}]"];
if ([jsonObj isKindOfClass:[NSArray class]]) {
for (id obj in jsonObj) {
if ([obj isKindOfClass:[NSDictionary class]]) {
NSString *name = [obj objectForKey:#"pat_firstname"];
NSLog(#"name %#", name);
}
}
}
[parser release];
Try Below Code.
NSString* jsonString;
//jsonString suppose this String has That JSON Response.
SBJSON *parser = [[[SBJSON alloc] init] autorelease];
NSDictionary *jsonResponse = (NSDictionary*)[parser objectWithString:jsonString error:nil];
NSArray *pat_reg_noArray = [jsonResponse valueForKey:#"pat_reg_no"] ;
NSArray *app_start_timeArray= [jsonResponse valueForKey:#"app_start_time"] ;
NSArray*firstnameArray=[jsonResponse valueForKey:#"pat_firstname"];
I hope It 'll work.
The Array which you have posted belongs to someKey, so do the following
SBJSON *jsonParser = [[SBJSON alloc] init];
NSDictionary * dictionary = [jsonParser objectWithString:YourString];
NSArray * array = [dictionary objectForKey:someKey];
NSMutableArray *nameArray = [NSMutableArray new];
for (NSDictionary *dict in array)
{
[nameArray addObject:[dict objectForKey:#"pat_firstname"];
}
NSLog(#"x is %#",nameArray);
[jsonParser release];
Hope this will solve your problem...
Try this:
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSArray* array = [(NSDictionary*)[jsonString JSONValue] objectForKey:#"results"];

Values not appending to my NSMutableDictionary

I'm trying to add some vales to a NSMutableDictionary dynamically. However, using the following code, I'm adding values using the first letter as the key to a temporary dictionary and then finally adding it to my names dictionary but it just overwrites each value for it's corresponding key
NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] init] autorelease];
for (NSString *drugStr in listContents) {
NSString *substring = [drugStr substringToIndex:1];
[dictionary setValue:drugStr forKey:substring];
}
names = [[NSDictionary alloc] initWithDictionary:dictionary];
[dictionary release];
What am I doing wrong?
You should define your NSDictionary to use NSString as a key, and NSArray as a value.
Then you should just retrieve your value according to the given key. If the result is nil, then you need to create a new NSMutableArray, to which you add the value above. IF the result is not-nil, add the value to the array.
NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] init] autorelease];
for (NSString *drugStr in listContents) {
NSString *substring = [drugStr substringToIndex:1];
NSMutableArray *valueArray = (NSMutableArray*)[dictionary objectForKey:substring];
if(valueArray==nil){
NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:5];
[newArray addObject:drugStr];
[dictionary setObject:newArray forKey:substring];
}else{
[valueArray addObject:drugStr];
}
}
names = [[NSDictionary alloc] initWithDictionary:dictionary];
[dictionary release];

Best way to split and convert url params into string values

I would like to split a custom url for app opening in iPhone into values, my scheme would be something like:
appname://user=jonsmith&message=blah%20blah
Where I would like to be able to get "user" and "message" as two NSStrings. Any advice on best approach?
Assuming your url is in an NSURL object called url:
NSMutableDictionary *queryParams = [[NSMutableDictionary alloc] init];
NSArray *components = [[url query] componentsSeparatedByString:#"&"];
for (NSString *component in components) {
NSArray *pair = [component componentsSeparatedByString:#"="];
[queryParams setObject:[[pair objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding: NSMacOSRomanStringEncoding]
forKey:[pair objectAtIndex:0]];
}
...
[queryParams release];
Use Google's gtm_dictionaryWithHttpArgumentsString NSDictionary category
http://code.google.com/p/google-toolbox-for-mac/source/browse/trunk/Foundation/GTMNSDictionary%2BURLArguments.h
NSString* yourString = #"appname://user=jonsmith&message=blah%20blah";
NSString* queryString = [yourString substringFromIndex:strlen("appname://")];
NSArray* queryArray = [queryString componentsSeparatedByString:#"&"];
NSMutableDictionary* queryDict = [NSMutableDictionary dictionary];
for (NSString* query in queryArray) {
NSUInteger indexOfEqualsSign = [query rangeOfString:#"="].location;
if (indexOfEqualsSign != NSNotFound) {
NSString* key = [[query substringToIndex:indexOfEqualsSign] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* value = [[query substringFromIndex:indexOfEqualsSign+1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[queryDict setObject:value forKey:key];
}
}
return queryDict;
Use an NSScanner if you need to save more memory.