Hi I'm new to iphone development, I'm currently working with a project where I have a screen, in which user should enter their details, like username and password. I googled and find out about NSURLConnection for GET/POST/DELETE. I can GET data by the below codes,
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://************/api/Users"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Content-
Type"];
NSURLResponse *response;
NSData *GETData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:nil];
NSString *ResultData = [[NSString alloc] initWithBytes:[GETData bytes] length:[GETData
length] encoding: NSASCIIStringEncoding];
NSLog(#"ResultData: %#", ResultData);
But for POST method, i doesn't get any ideas of , how it functions and how it store record to sql server database, can't understand whether it s storing data or not, i tried the following codes,
username = #"Aravind.k";
password = #"1234/";
email = #"sivaarwin#gmail.com";
NSString *post = [NSString stringWithFormat:#"FirstName=%#&LastName=%#&WorkEmailAddress=%#",
username, password, email];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://*********/api/Users"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8"
forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"request: %#", request);
NSLog(#"postData: %#", postData);
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:nil];
NSLog(#"POSTReply: %#", POSTReply);
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes]
length:[POSTReply length]
encoding:NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
Same api url for both GET and POST, any suggestions regarding POST and DELETE will be grateful, Thanks in advance.And how we can get notified as the entered data is stored into the server.
First off: not checking for errors automatically leads to down votes ;)
Please edit your code with full error checks!
When using a MIME type application/x-www-form-urlencoded you need to properly encode the parameters.
I would suggest, to create a NSDictionary holding your parameters, e.g.:
NSDictionary* params = #{#"FirstName": firstName, #"LastName": lastName, #"password": password};
and then use the approach described in the following link to get an encoded parameter string suitable for using as a body data for a application/x-www-form-urlencoded message:
How to send multiple parameterts to PHP server in HTTP post
The link above implements a Category and a method dataFormURLEncoded for a NSDictionary which returns an encoded string in a NSData object:
NSData* postData = [params dataFormURLEncoded];
Note: The MIME type application/x-www-form-urlencoded does not have a charset parameter. It will be ignored by the server. You should set the header like below:
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
Otherwise, your code should work. I would strongly recommend to use the asynchronous version of the convenient method:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request
queue:(NSOperationQueue *)queue
completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
Related
I'm new to iOS and i'm using the following code to make API Calls.
-(NSData *)sendDataToServer:(NSString*)url :(NSString*)params
{
NSString *postDataString = [params stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"postDataString :%#",postDataString);
NSData *postData = [postDataString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *urlReq = [NSString stringWithFormat:#"%#", url];
[request setURL:[NSURL URLWithString:urlReq]];
[request setTimeoutInterval:180];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"response in Server: %#",responseString);
return responseData;
}
I'm sending the following string as params to the above method. If I send the following data without special characters, I'm getting the success response.
If i Add any special charters as like (&) with json I'm always getting the invalid response, that is the server always returns null.
So Can anyone please provide any suggestion to get the right response when using json string with Special characters like '&' etc.,
submited_data={"safty_compliance_fields":[{"safty_compliance_id":"641","fieldName":"sc1","fieldType":"editText","fieldValue":"wedgies Ig"},{"safty_compliance_id":"642","fieldName":"sc2","fieldType":"editText","fieldValue":"het &"}],"status_id":"2","product_detail":[{"dynamic_fields_id":"639","fieldName":"p1","fieldType":"editText","fieldValue":"data1"},{"dynamic_fields_id":"640","fieldName":"p2","fieldType":"editText","fieldValue":"data2"}],"inspection_id":"3","second_level":[{"questions":[{"checkListValue":"NO","checkListCommentValue":"Jgkjgjkj","sub_category_id":"452","checkListName":"sl1"},{"checkListValue":"YES","checkListCommentValue":"jk","sub_category_id":"453","checkListName":"sl2"},{"checkListValue":"YES","checkListCommentValue":"gh","sub_category_id":"455","checkListName":"sl3"},{"checkListValue":"YES","checkListCommentValue":"nm","sub_category_id":"456","checkListName":"sl4"}],"title":"sl1","entity_second_level_entry_id":"130"},{"questions":[{"checkListValue":"YES","checkListCommentValue":"Bonn","sub_category_id":"454","checkListName":"s22"}],"title":"s211","entity_second_level_entry_id":"131"}],"comment":"Jgkjgjkj","status":"Ongoing"}
You didn't post the percent encoded string, but the original string.
NSString *AuthToken = [[NSUserDefaults standardUserDefaults]
stringForKey:#"AuthToken"];
NSString* json =[NSString stringWithFormat:#"{'DeviceId':'%#','DeviceType':'iOS','UM_Identifier':'%#','AuthToken':'%#','Query':'all'}", deviceId, userEmail, AuthToken];
NSString *post =[[NSString alloc] initWithFormat:#"jinpAllCustDetails=%#",json];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"http://www.google.com"]];
NSData *postData = [post dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
In above code :
Auth token received from last webservice response is saved in NSUserdefaults,
then used for next webservice request.
So for Eg.
Send auth token : z71VxyfVlBxvNKJ01m64a4oKV9lWEv+fFhHxi+7zyRw=
But server would receives it as :z71VxyfVlBxvNKJ01m64a4oKV9lWEv fFhHxi 7zyRw=
ie All occurrences of "+" are replaced by " ". So server considers it as an invalid auth token and the webservices request returns a result accordingly.
Help me to fix this, thanks in advance
That isn't valid JSON as strings should be surrounded with ". Create an NSDictionary of the values and use NSJSONSerialization to create the JSON string, which you know will be valid:
NSDictionary *values = #[
#"DeviceId": deviceId,
#"DeviceType": #"iOS",
#"UM_Identifier": userEmail,
#"AuthToken": authToken,
#"Query": #"all"
];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:values
options:0
error:&error];
NSAssert(jsonData != nil, #"Failed to create JSON data");
NSString jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
I have create an application that send two POST parameters to aspx server and it's save data in database.
It's an Iphone Application.
Here's the code:
NSString *post = [NSString stringWithFormat:#"name=%#&number=%#",
name,number];
NSString *capturedpost = [post
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *postData = [capturedpost dataUsingEncoding:NSUTF8StringEncoding];
//NSString *postLength = [NSString stringWithFormat:#"%d", [postData
length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http:/www.myurl.aspx"]];
[request setHTTPMethod:#"POST"];
//[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
//[request setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request
returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler
bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
But on server, the string "number" that contain the telephone number like "+393333..." save in db the number without the "+".
How can I do?
The server side works fine, because the same App on Android that do same request work perfect!
OK, thanks to "holex" I successfully encode the URL in this way:
NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)post,
NULL,
(CFStringRef)#"+",
kCFStringEncodingUTF8 ));
And the "+" saved correctly in db!
Before you read this please keep in mind that I am an Objective C programmer trying to help debug a server problem with a C# programmer who knows nothing about what I do.
I am sending a SOAP packet to a .net/c# side and the server receives nulls for the variables. When the url and variable string is put in the browser I get the proper response.
The post logs out to "?help=1& email=test#email.net & password=testpassword" but i keep getting "Result=Error&Details=Object reference not set to an instance of an object." back for my return string.
NSString *post = [NSString stringWithFormat:#"?help=1& email=? & password=%#",userEmail, userPassword];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:LOGIN_SERVICE]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"multipart/form-data" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//Submit the Post:
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
/NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//Extract Return:
NSString *returnString = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
Your email variable within the format string wasnt being populated. And also, why do you have spaces in your post data? I imagine this is causing your issues. Because your data can contain spaces, you'll need to escape them.
Instead of:
NSString *post = [NSString stringWithFormat:#"?help=1& email=? & password=%#",userEmail, userPassword];
Try:
NSString* escapedUserEmail = [userEmail stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString* escapedUserPassword = [userPassword stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString *post = [NSString stringWithFormat:#"?help=1&email=%#&password=%#",escapedUserEmail, escapedUserPassword];
For more reading on the topic, refer to: http://deusty.blogspot.com/2006/11/sending-http-get-and-post-from-cocoa.html
I am currently connecting my iOS native app to a facebook page in order to post a message to that wall. I can access the wall but for some reason there's no message text set. I asked the user for 'publish_stream' permissions.
Any idea what I'm doing wrong? Here's my code:
NSMutableDictionary *message = [NSDictionary dictionaryWithObjectsAndKeys:#"some text", #"message", #"http://path/to/itunes/", #"link", nil];
NSString *changeJSON = [message JSONRepresentation];
NSLog(#"changeJSON: %#", changeJSON);
NSData *myPostData = [changeJSON dataUsingEncoding:NSUTF8StringEncoding];
NSString *myURL = [NSString stringWithFormat:#"https://graph.facebook.com/pageId/feed?access_token=%#", facebook.accessToken];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:myURL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [myPostData length] ] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: myPostData];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"return string: %#", returnString);
[facebook logout:self];
The string which is encoded to a NSData object is the following:
{"message":"some text","link":"http://path/to/itunes/"}
Thanks and have a nice day :-)
It looks like you're attempting to post JSON to the GraphAPI? If so, you can't post JSON to Facebook, but instead have to use parameters when posting (either query string or HTTP request parameters).
All posting actions are done via HTTP POST with parameters and all responses are done in JSON. You can read more on this via the Graph API reference under publishing.
See: POST Reference.