UItextFields Data to JSON - objective-c

i have two UItextFields, userNameTextField and passwordTextField and a UIbutton connection. I would like to have what the user typed in the userNametextField and the passwordTextField, How i can do this please ?? thanks for your answer.
#pragma mark - User auhtentification
-(IBAction)userAuthentificate{
BOOL loginValid = YES;
BOOL passwordValid = YES; // Not specified yet
// contrioll d'interfac__ on test login et password
if (loginValid && passwordValid) {
NSString *jsonRequest = #"{\"login\":\"Samir\",\"password\":\"test\",\"mail\":\"test#gmail.com\"}";
// NSString *jsonRequest = #"{\"login\":\"Samir\",\"password\":\"test\",\"mail\":\"samir#gmail.com\",\"editor\":\"1\"}";
NSString *request_url =#"http:.../register"; // Url WS
NSURL *url = [NSURL URLWithString:request_url];
self.currentRequest = [ASIFormDataRequest requestWithURL:url];
currentRequest.delegate =self;
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[self.currentRequest appendPostData:requestData];
[self.currentRequest setRequestMethod:#"POST"];
[self.currentRequest startSynchronous];
}
}

You can put something like this in the place of your jsonRequest string (the code uses the SBJson framework):
NSDictionary *container = [[NSDictionary alloc] initWithObjectsAndKeys:
[loginTextField text], #"login",
[passwordTextField text], #"password",
[mailTextField text], #"mail"];
NSString *jsonString = [container JSONRepresentation];
// don't forget to release container if not using ARC AFTER creating the NSData object

How about a simple string replacement?
NSString *jsonRequest = [NSString stringWithFormat:#"{\"login\":\"%#\",\"password\":\"%#\",\"mail\":\"%#\"}", userNameTextField.text, passwordTextField.text, emailtextField.text];

Use
NSString *jsonRequest = [NSString stringWithFormat:#"{\"login\":\""%#"\",\"password\":\""%#"\",\"mail\":\"test#gmail.com\"}",userNameTextField.text,passwordTextField.text];

Related

Error 400 and 415 when exchanging code for access_token

I am writing an application to authorise itself into Spotify. I used the node app.js example to get things working and an now re-writing natively into Objective C. I have extracted the authorisation code via a callback function
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://accounts.spotify.com/api/token"]];
request.HTTPMethod = #"POST";
// put in the header fields
NSString *headerString = [NSString stringWithFormat:#"%#:%#",clientID,clientSecret];
NSData *nsdata = [headerString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];
base64Encoded = [ NSString stringWithFormat:#"Basic %#", base64Encoded];
[request setValue:base64Encoded forHTTPHeaderField:#"Authorization"];
NSLog(#"request.header %#", request.allHTTPHeaderFields.description);
// put in the body form
NSString * stringData = [NSString stringWithFormat:#"grant_type:%#, code:%#, redirect_uri:\"%#\"", #"authorization_code",authorisationCode,redirectUri];
NSData * requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
NSLog(#"request.body %#", [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding]);
I then post this request and get
{"error":"server_error","error_description":"Unexpected status: 415"}
returned.
I have found a variety of questions on this topic revolving around the Content-Type needing to be application/x-www-form-urlencoded but this was no direct cure.
Anyone got any suggestions for me?
I found the answer here NSURLRequest : Post data and read the posted page
It appears that the raw data within the HTTPBody needs to be formatted differently - no JSON at all. The above link has a useful function which I updated slightly
-(NSData*)encodeDictionary:(NSDictionary*)dictionary {
NSMutableArray *parts = [[NSMutableArray alloc] init];
for (NSString *key in dictionary) {
NSString *encodedValue = [[dictionary objectForKey:key] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPasswordAllowedCharacterSet]];
NSString *encodedKey = [key stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPasswordAllowedCharacterSet]];
NSString *part = [NSString stringWithFormat: #"%#=%#", encodedKey, encodedValue];
[parts addObject:part];
}
NSString *encodedDictionary = [parts componentsJoinedByString:#"&"];
return [encodedDictionary dataUsingEncoding:NSUTF8StringEncoding];
}
and ..
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
//NSLog(#"request.header %#", request.allHTTPHeaderFields.description);
// put in the body form using the new function
NSDictionary * parameters = [[NSDictionary alloc] initWithObjectsAndKeys:#"authorization_code",#"grant_type",authorisationCode,#"code",redirectUri,#"redirect_uri", nil ];
NSData * requestBodyData = [self encodeDictionary:parameters];
request.HTTPBody = requestBodyData;

TBXML with NSData in Xcode

I have a URL that returns a pretty flat XML file: <entries><title>val1</title><author>Bob</author></entries> The code runs ok:
NSString *urlString = [NSString stringWithFormat:#"http://www.somesite.php?qid=%d", __inum];
NSLog(#"urlString = %#", urlString);
NSURLResponse * response = nil;
NSError * error = nil;
NSURLRequest * urlRequest = [NSURLRequest requestWithURL: [NSURL URLWithString:urlString]];
NSData * myData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSLog(#"%#", myData);
TBXML *sourceXML = [[TBXML alloc] initWithXMLData:myData error:nil];
TBXMLElement *rootElement = sourceXML.rootXMLElement;
if (rootElement) {
NSLog(#"Root element found...");
TBXMLElement *qaElement1 = [TBXML childElementNamed:#"title" parentElement:rootElement];
if (qaElement1) {
NSString *idAttribute = [TBXML valueOfAttributeNamed:#"title" forElement:qaElement1];
NSLog(#"Got to the 1st call for idAttribute... %#", idAttribute);
}
else { NSLog(#"There is no value for title..."); }
}
else { NSLog(#"Root element must be null..."); }
}
It finds the root element and gets to the call for valueOfAttribute:#"title" but the value is always (null).
So my question: do I have to do something to convert the NSData back to man readable (I was under the impression TBXML gave that option to work with the NSData and did the calculation). If not, what is the call to create (and then use) an NSString in UTF8 from 'myData'?
what is the call to create (and then use) an NSString in UTF8 from 'myData'?
use initWithData:encoding:
NSString *str = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
or stringWithUTF8String: if you know myData is null-terminated UTF8 string
NSString *str = [NSString stringWithUTF8String:[myData bytes]];
Do not ignore error.
NSError *error = nil;
TBXML *sourceXML = [[TBXML alloc] initWithXMLData:myData error:&error];
if (error) {
// handle it, at least log it
}

Parse JSON file into POST request Objective C

I parse an JSON File into an Dictionary and in a further step I want to build a post request for couchDB.
The parsing works fine, but if I post I get an error. I thinks it has something to do with my escape sequence in the post string.
HereĀ“s the code:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"json"];
NSString *fileContent = [[NSString alloc] initWithContentsOfFile:filePath];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
// getting the data from file
NSString *_id = (NSString *) [data objectForKey:#"_id"];
NSString *rev_ = self.rev;
NSString *_herausgeber = (NSString *) [data objectForKey:#"Herausgeber"];
NSString *_nummer = (NSString *) [data objectForKey:#"Nummer"];
NSNumber *_deckung = [data objectForKey:#"Deckung"];
NSString *_waerhung = (NSString *) [data valueForKey:#"Waehrung"];
NSDictionary *_inhaber = (NSDictionary *) [data objectForKey:#"Inhaber"];
NSString *_name = (NSString *) [_inhaber objectForKey:#"Name"];
NSString *_vorname = (NSString *) [_inhaber objectForKey:#"Vorname"];
NSNumber *_maennlich = (NSNumber *) [_inhaber objectForKey:#"maennlich"];
NSArray *_hobbys = (NSArray *) [_inhaber objectForKey:#"Hobbys"];
NSString *_hobby0 = [_hobbys objectAtIndex:0];
NSString *_hobby1 = [_hobbys objectAtIndex:1];
NSString *_hobby2 = [_hobbys objectAtIndex:2];
NSNumber *_alter = (NSNumber *) [_inhaber objectForKey:#"Alter"];
NSArray * _kinder = (NSArray *) [_inhaber objectForKey:#"Kinder"];
NSString *_kind0 = [_kinder objectAtIndex:0];
NSString *_kind1 = [_kinder objectAtIndex:1];
NSString *_kind2 = [_kinder objectAtIndex:2];
NSString *_partner = (NSString *) [_inhaber objectForKey:#"Partner"];
[parser release];
//post string:
NSString *post = [NSString stringWithFormat:#"{\"_id\":\"%#\",\"_rev\":\"%#\",\"Herausgeber\":\"%#\",\"Nummer\":\"%#\",\"Deckung\":%#,\"Waehrung\":\"%#\",\"Inhaber\":{\"Name\":\"%#\",\"Vorname\":\"%#\",\"maennlich\":%#,\"Hobbys\":[\"%#\",\"%#\",\"%#\"],\"Alter\":%#,\"Kinder\":[\"%#\",\"%#\",\"%#\"],\"Partner\":%#}}",_id,rev_,_herausgeber,_nummer,_deckung,_waerhung,_name,_vorname,_maennlich,_hobby0,_hobby1,_hobby2,_alter,_kind0,_kind1,_kind2,_partner];
//post header:
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:cdbURL]];
[request setHTTPMethod:#"PUT"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
The Error I get:
Reply: {"error":"bad_request","reason":"invalid UTF-8 JSON:
<<\"{\\"_id\\":\\"161eba7093799b610502bdfba5004281\\",\\"_rev\\":\\"199-bb065cbd0a365b188fc492cc22453d74\\",\\"Herausgeber\\":\\"SAP\\",\\"Nummer\\":\\"1234-5678-9012-3456\\",\\"Deckung\\":2000000,\\"Waehrung\\":\\"Franc\\",\\"Inhaber\\":{\\"Name\\":\\"Mustermann\\",\\"Vorname\\":\\"Max\\",\\"maennlich\\":1,\\"Hobbys\\":[\\"Reiten\\",\\"Golfen\\",\\"Lesen\\"],\\"Alter\\":42,\\"Kinder\\":[\\"Max\\",\\"Moritz\\",\\"Lisa\\"],\\"Partner\\":}}\">>"}
How can I solve this problem?
Personally, I would avoid constructing the JSON post-string myself and instead use SBJson's [NSObject JSONRepresentation] function.
Then you could fill an NSDictionary and have the API construct the JSON for you.
NSString *_id = #"161";
NSString *_rev = #"199";
NSString *_herausgeber = #"SAP";
NSMutableDictionary *toPost = [NSMutableDictionary dictionary];
[toPost setObject:_id forKey:#"_id"];
[toPost setObject:_rev forKey:#"_rev"];
[toPost setObject:_herausgeber forKey:#"Herausgeber"];
NSLog(#"JSON: %#", [toPost JSONRepresentation]);
Gives:
JSON: {"_id":"161","_rev":"199","Herausgeber":"SAP"}

Want to split the JSON from the URL not the response

I want to split the json part from this URL in my iPhone application.
http://vkontakte.ru/login_success.html#session={"expire":"1272008089","mid":"100172","secret":"9c8d8f0305","sid":"1131703552161ae352a1256402e3140d7cbde41b1602a93d15472c82"}
I tried and and saved the JSON into a NSString but what i am getting is
http://vkontakte.ru/api/login_success.html?session=%7B%22mid%22:113158415,%22secret%22:%227ce58bfcd3%22,%22sid%22:%2203831b43c1bb992f9477efbfe96e83f6ecff1c1b661315ac0a20719cf57a44%22,%22expire%22:0%7D
This is not coming in JSOn Format. Below is my code
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
NSError* error;
NSLog (#"json path %#",url);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request1 = [NSURLRequest requestWithURL:url];
NSString *json_string = [url absoluteString];
NSArray *arr = [json_string componentsSeparatedByString:#"="];
json_string = [arr objectAtIndex:1];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [json_string JSONValue];
NSLog(#"%#",error);
// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey:#"secret "], [[status objectForKey:#"mid"] objectForKey:#"sid"]);
}
return YES;
}
How can move further?
Try replacing:
NSString *json_string = [url absoluteString];
with
NSString *json_string = [[url absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];.
That's a really strange thing you're doing, though. Why does the URL have JSON in it?

Leaks in passing the request using URL at NSString, Objective-C

I getting the leak in this method even the allocated nsstring is released.
Now I am taken stringWithFormat, but still it is showing the leak at "NSData *returnData=...." line
-(BOOL)getTicket:(NSString*)userName passWord:(NSString*)aPassword isLogin:(BOOL)isLogin
{
NSString* str=#"";
if (isLogin == YES)
{
str =[NSString stringWithFormat:#"AGENT=true&LOGIN_ID=%#&PASSWORD=%#",[self _encodeString:userName],[self _encodeString:aPassword]];
}
else if (isLogin == NO)
{
str =[NSString stringWithFormat:#"AGENT=true&LOGIN_ID=%#&PASSWORD=%#",[self _encodeString:userName],[self _encodeString:aPassword]];
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:25.0];
[request setHTTPMethod: #"POST"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
printf("\n returnString in getticket:%s",[returnString UTF8String]);
NSRange textRange;
textRange =[returnString rangeOfString:#"TICKET"];
if(textRange.location != NSNotFound)
{
NSArray* splitValues = [returnString componentsSeparatedByString:#"TICKET="];
NSString* str1 = [splitValues objectAtIndex:1];
NSArray* splitValues1 = [str1 componentsSeparatedByString:#"RESULT"];
NSString* ticket1 = [splitValues1 objectAtIndex:0];
self.ticket = ticket1;
self.isCorrectLogin = YES;
[returnString release];
return YES;
}
else
{
self.isCorrectLogin = NO;
[returnString release];
return NO;
}
return NO;
}
Please help me out of this problem.
Macbirdie is correct in that composing a string using stringByAppendingString: is horribly inefficient. I would suggest using +stringWithFormat: instead.
As for the leak, if the leak is where you say it is, then it might be a leak in the underlying framework (and it might be a false positive). Post the backtrace of the leaked object (which can be had from the Allocations instrument).