EXC_BAD_ACCESS error occured when using stringWithFormat - objective-c

this is my header section:
#interface RootViewController : UIViewController
{
NSString *status_id;
}
in the controller file, i am assigning the variable:
- (void)updateStatus
{
NSURL *url = [NSURL URLWithString:#"http://localhost/RightNow/API/status.json"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
NSString *response = [NSString alloc];
NSError *error2;
NSData* data = [response dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error2];
status_id = [json objectForKey:#"id"];
}
now, when i try to use the status_id again, i get the error
- (IBAction)likeClick:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://localhost/RightNow/API/vote"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:status_id forKey:#"id"]; //The error comes here
[request setPostValue:#"like" forKey:#"vote"];
[request startSynchronous];
}
sorry about my bad english.
please help me, thank you!

[json objectForKey:#"id"]; will return the object in autorelease pool. You either need to send a copy message to it like
status_id = [[json objectForKey:#"id"] copy];
and release it when appropriate (if not using ARC)

Related

Posting JSON data to server

I am trying to post and JSON data to server.
My JSON is:
{
“username”:”sample”,
“password” : “password-1”
}
The way I am sending it to server is:
NSError *error;
NSString *data = [NSString stringWithFormat:#"{\"username\":\"%#\",\"password\":\"%#\"}",_textFieldUserName.text,_textFieldPasssword.text];
NSData *postData = [data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSData *jsonData = [NSJSONSerialization JSONObjectWithData:postData options:0 error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"My URL"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:requestHandler options:0 error:&error];
NSLog(#"resposne dicionary is %#",responseDictionary);
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
The JsonData that is created is a valid JSON accepted by the server.
But the app is crashing and the error is:
-[__NSCFDictionary length]: unrecognized selector sent to instance 0x1702654c0
what is wrong that i am doing here?
I always use this method in my apps to perform API calls. This is the post method. It is asynchronous so you can specify a callback to be called when the server answer.
-(void)placePostRequestWithURL:(NSString *)action withData:(NSDictionary *)dataToSend withHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *error))ourBlock {
NSString *urlString = [NSString stringWithFormat:#"%#", action];
NSLog(#"%#", urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dataToSend options:0 error:&error];
NSString *jsonString;
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *requestData = [NSData dataWithBytes:[jsonString UTF8String] length:[jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
}
}
You can easily call it:
- (void) login:(NSDictionary *)data
calledBy:(id)calledBy
withSuccess:(SEL)successCallback
andFailure:(SEL)failureCallback{
[self placePostRequestWithURL:#"yourActionUrl"
withData:data
withHandler:^(NSURLResponse *response, NSData *rawData, NSError *error) {
NSString *string = [[NSString alloc] initWithData:rawData
encoding:NSUTF8StringEncoding];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
NSLog(#"%ld", (long)code);
if (!(code >= 200 && code < 300)) {
NSLog(#"ERROR (%ld): %#", (long)code, string);
[calledBy performSelector:failureCallback withObject:string];
} else {
NSLog(#"OK");
NSDictionary *result = [NSDictionary dictionaryWithObjectsAndKeys:
string, #"id",
nil];
[calledBy performSelector:successCallback withObject:result];
}
}];
}
And finally, you invocation:
NSDictionary *dataToSend = [NSDictionary dictionaryWithObjectsAndKeys:
_textFieldUserName.text, #"username",
_textFieldPasssword.text, #"password", nil];
[self login:dataToSend
calledBy:self
withSuccess:#selector(loginDidEnd:)
andFailure:#selector(loginFailure:)];
Don't forget to define your callbacks:
- (void)loginDidEnd:(id)result{
NSLog(#"loginDidEnd:");
// Do your actions
}
- (void)loginFailure:(id)result{
NSLog(#"loginFailure:");
// Do your actions
}
First you create an NSString* that is supposed to contain JSON data. This doesn't work in general if the username and password contain any unusual characters. For example, I make sure that I have a quotation mark in my password to make sure that stupid software crashes.
You turn that string into an NSData* using ASCII encoding. So if my username contains any characters that are not in the ASCII character set, what you get is nonsense.
You then use the parser to turn this into a dictionary or array, but store the result into an NSData. Chances are that the parse fails and you get nil, otherwise you get an NSDictionary* or an NSArray*, but most definitely not an NSData*.
Here's how you do it properly: You create a dictionary, and then turn it into NSData.
NSDictionary* dict = #{ #"username": _textFieldUserName.text,
#"password": _textFieldPasssword.text };
NSError* error;
NSData* data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
That's it.
try this:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:#"My URL"];
if (!request) NSLog(#"Error creating the URL Request");
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"text/json" forHTTPHeaderField:#"Content-Type"];
NSLog(#"will create connection");
// Send a synchronous request
NSURLResponse * response = nil;
NSError * NSURLRequestError = nil;
NSData * responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&NSURLRequestError];

How to send json data in the Http request to POST Method in JSON Parsing

I need to Parse below string to POST method in iOS
"jsonData":{"empId":"cxvd","password":"sfsd"}
But I m getting the error as
Res: Tomcat Error
HTTP Status 400 - Required String parameter 'jsonData' is not present
//------ Method I have used to Parse is ---------- //
+(void) requestToServerForLogin:(NSString*)userName andPassward: (NSString*)password onCompletion:(RequestCompletionHandler) handler
{
NSString *url = [Ip stringByAppendingString:#"login"];
NSString *jsonString = [NSString stringWithFormat:#"\"jsonData\":{\"empId\":\"%#\",\"password\":\"%#\"}",
userName,
password ];
NSURL *nsurl = [NSURL URLWithString:url];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:nsurl];
[urlRequest setTimeoutInterval:60.0f];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:#"application/json"
forHTTPHeaderField:#"Content-type"];
NSString *body = jsonString1;
[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"urlRequest :%#",[body dataUsingEncoding:NSUTF8StringEncoding]);
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data1, NSError *error)
{
NSString *res = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
if(handler) handler(res,error);
}];
}
Thanks in advance
There is way to much code. The substringToIndex and substringFromIndex are wrong, should not be in the code.
Use the literal syntax for the dictionaries:
NSDictionary *jsonDict = #{#"jsonData":#{#"password":password, #"empId":userName}};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];

Reddit API ios modhash/cookie issue

Im' trying to submit to Reddit via my iOS app. I can login fine and am sent back a modhash and a cookie which I save via NSUserDefaults.
The issue is when I post the data I keep getting "USER_REQUIRED" as the response, even though I have included the modhash in the post and set my session cookie. I have even included the following in my app delegate:
[[NSHTTPCookieStorage sharedHTTPCookieStorage]
setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
But it still doesn't work. Here is my code:
-(void) post {
NSString *modhash2 = [[NSUserDefaults standardUserDefaults]
objectForKey:#"modhash"];
NSString *urlString = [NSString
stringWithFormat:#"https://ssl.reddit.com/api/submit"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSString *contentType = [NSString stringWithFormat:#"application/x-www-form-urlencoded;"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[request addValue:redditCookie forHTTPHeaderField:#"Cookie"];
[request setHTTPMethod:#"POST"];
NSString *httpBody = [NSString stringWithFormat
:#" ?uh=%#&kind=link&url=%#&sr=%#&title=%#&r=%#&api_type=json",
modhash2,
#"www.google.com",
#"test",
#"Google.com",
#"test"];
[request setHTTPBody:[httpBody dataUsingEncoding:NSASCIIStringEncoding]];
NSURLResponse* response;
NSError* error = nil;
NSData* result = [NSURLConnection
sendSynchronousRequest:request
returningResponse:&response
error:&error];
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:result
options:NSJSONReadingMutableContainers
error:nil];
NSDictionary *responseJSON = [json valueForKey:#"json"];
NSLog(#"RETURN: %#",responseJSON);
}
Any ideas?

iphone SDK: How to post data to a url?

This may be a duplicate question but i could not find my answer when searching. So, How do i post data to a url? Heres what i got so far:
NSString *url = #"https://localhost/login.php";
NSURL *urlr = [NSURL URLWithString:url];
NSMutableURLRequest *urlre = [[NSMutableURLRequest alloc] init];
[urlre setURL:[NSURL URLWithString:url]];
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
NSString *user = [defs stringForKey:#"User"];
NSString *pass = [defs stringForKey:#"Pass"];
NSInteger *version = [defs integerForKey:#"Version"];
NSString *bodyData = [[NSString alloc] initWithFormat:#"user=%#&password=%#&version=%d",user,pass,version];
NSData *body = [bodyData dataUsingEncoding:NSASCIIStringEncoding];
NSURLResponse *response = nil;
NSError *error = nil;
[urlre setHTTPMethod:#"POST"];
[urlre setValue:[[NSString alloc] initWithFormat:#"%d",[body length]] forHTTPHeaderField:#"Content-Length"];
[urlre setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlre setHTTPBody:body];
NSData *dataThis = [NSURLConnection sendSynchronousRequest:urlre returningResponse:&response error:&error];
if(dataThis)
{
NSLog(#"Connect Success");
} else {
NSLog(#"%#",[error localizedDescription]);
}
Is the above correct? In my
-(void) connection:(NSURLConnection*)connection didReceiveData:(NSData *)data
event, I get nothing. Even in the didFinishLoading it gets nothing with NSLog. Please help.
Have you set a delegate for your request?
Why don't you have a look at using a framework like ASIHTTPRequest, makes things so simple. Check it out http://allseeing-i.com/ASIHTTPRequest/

How can I create an new issue in redmine use objective-c

I want to create an new issue, I use the code below:
NSString *xml = [NSString stringWithFormat:#"<?xml version=\"1.0\"?>\n"
"<issue>\n"
"<subject>test create</subject>\n"
"<project_id>2</project_id>\n"
"<priority_id>2</priority_id>\n"
"<status_id>1</status_id>\n"
"<tracker_id>1</tracker_id>\n"
"<assigned_to_id>1</assigned_to_id>\n"
"</issue>"];
NSDictionary *nameDic = [[NSUserDefaults standardUserDefaults] objectForKey:ActiveShare_Account];
NSString *url = [NSString stringWithFormat:#"http://%#:%#%#/issues.xml", [nameDic objectForKey:#"username"], [nameDic objectForKey:#"password"], BASICE_URL];
NSURL *urlU = [NSURL URLWithString:url];
NSLog(#"add new issue: %#", url);
ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:urlU];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"Content-Type" value:#"application/xml"];
[request setPostBody:(NSMutableData *)[xml dataUsingEncoding:NSUTF8StringEncoding]];
request.delegate = self;
[request startSynchronous];
NSError *error = [request error];
if (error) {
NSLog(#"error: %#", error);
}
else {
NSLog(#"send ok");
}
but I can not create the issue, the address is correct, I use the address successfully update the issue and delete issue, Could you someone can help me? Thanks