NSMutableURLRequest not changing HTTPMethod - ios

I have the following method in XCode:
- (void)makeRequest:(NSString *)wPin withMethod:(NSString *)HTTPMethod passValue:(NSString *)wVal {
#try {
NSString *params = #"";
NSString *postString;
NSData *postData;
NSString *method;
if ([HTTPMethod isEqualToString:#"GET"]) {
params = [NSString stringWithFormat:#"?pin=%#", wPin];
method = #"Retrieving data from";
} else {
postString = [NSString stringWithFormat:#"pin=%#&val=%#", wPin, wVal];
postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
method = [NSString stringWithFormat:#"Passing '%#' to", postString];
}
NSString *requestURL = [NSString stringWithFormat:#"%#%#", homeURL, params];
NSLog(#"%# '%#'", method, requestURL);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:requestURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:0];
NSString *postLength = [[NSString alloc] initWithFormat:#"%lu", (unsigned long)[postData length]];
[request setHTTPMethod:HTTPMethod];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSString *postBody = [[NSString alloc] initWithBytes: [request.HTTPBody bytes] length: [request.HTTPBody length] encoding:NSUTF8StringEncoding];
NSLog(#"%#", postBody);
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate: self];
if (conn) { //Makes connection
}
}
#catch (NSException *e) {
NSLog(#"Exception %#", e);
}
}
When I call this method using:
[self makeRequest:wPin withMethod:#"GET" passValue:#""];
My server logs a healthy GET request, and sends me back the right data, and I parse it... it works, no problem.
However, when I call this method using:
[self makeRequest:wPin withMethod:#"POST" passValue:wState];
My server still logs the request method as "GET". I've even tried setting the HTTPMethod directly:
[request setHTTPMethod:#"POST"];
And my server still logs a "GET" request.
FYI: I developed the same app in JavaScript, and everything works fine (Server handles GET and POST correctly).
Here is my app console output:
(on load)
2015-01-28 10:25:08.324 Switch[2977:132599] Retrieving data from '<my server>?pin=18'
2015-01-28 10:25:08.330 Switch[2977:132599] Retrieving data from '<my server>?pin=23'
2015-01-28 10:25:08.611 Switch[2977:132599] 18OFF
2015-01-28 10:25:08.626 Switch[2977:132599] 23ON
(when I send three POST requests)
2015-01-28 10:25:28.842 Switch[2977:132599] Passing 'pin=18&val=1' to '<my server>'
2015-01-28 10:25:28.843 Switch[2977:132599] pin=18&val=1
2015-01-28 10:28:12.189 Switch[2977:132599] Passing 'pin=18&val=0' to '<my server>'
2015-01-28 10:28:12.190 Switch[2977:132599] pin=18&val=0
2015-01-28 10:28:13.702 Switch[2977:132599] Passing 'pin=23&val=0' to '<my server>'
2015-01-28 10:28:13.703 Switch[2977:132599] pin=23&val=0
Also, when you see something like "pin=18&val=1" in the output, note that's just an NSLog of the postBody before it sends. That's not a server response, unlike the "18OFF" you see in the output.

Try changing encoding scheme,
[postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

The problem was with the way the DNS works with my server. I have to circumvent port 80, so when my domain name is pointed to it's proper port to reach my router, I receive an "Object Moved" response from POST requests unless I enter my server's IP manually. This somehow means the POST request becomes a GET request before reaching my page. In using direct IP, the app works. I'll have to sort this issue out elsewhere. Thanks to all who tried helping!
(The good news is, NSMutableURLRequest works!)

Related

Call function on Server from iOS app - Objective C

If you are familiar with Parse.com's Javascript SDK, this is what I am trying to do for my own server for my iOS app (Objective-c). I want to be able to send some a string to the function that is on my server, have the server run its function and then return a string to the app or some xml or JSON data.
Is this even possible?
I am new to doing something like this having an app make a call to a server. I have looked into opening a port on my server, but have been unable to find a way to receive data back to the iOS app. (I found this lib but its for OS X https://github.com/armadsen/ORSSerialPort). Also Im not sure if I have a function run with an open port on the server. So how can I set it up so I can make a call to my server and run a function?
Any help would be much appreciated.
You just need to POST data to your server.
Port could be anything you want.
Host your script with a domain url so that you can make network request publicly.
You can try this function:
-(NSData *)post:(NSString *)postString url:(NSString*)urlString{
//Response data object
NSData *returnData = [[NSData alloc]init];
//Build the Request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
//Send the Request
returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
//Get the Result of Request
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
bool debug = YES;
if (debug && response) {
NSLog(#"Response >>>> %#",response);
}
return returnData;
}
And here is how you use it:
NSString *postString = [NSString stringWithFormat:#"param=%#",param];
NSString *urlString = #"https://www.yourapi.com/yourscript.py";
NSData *returnData = [self post:postString url:urlString];
PHP
<?php
$response=array();
if(isset($_POST['param'])){
$response['success'] = true;
$response['message'] = 'received param = '.$_POST['param'];
}else{
$response['success'] = false;
$response['message'] = 'did not receive param';
}
$json = json_encode($response);
echo $json;

NSHTTPURLResponse release message sent to deallocated instance

I have the following code to get data from server;
-(void)loginForFaceBook
{
GTMOAuth2ViewControllerTouch *viewController;
viewController = [[GTMOAuth2ViewControllerTouch alloc]
initWithScope:#"https://www.googleapis.com/auth/plus.me"
clientID:#"27615...6qdi60qjmachs.apps.googleusercontent.com"
clientSecret:#"Fs8A...u2PH"
keychainItemName:#"OAuth2 Sample:
Google+"
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)];
[[self navigationController] pushViewController:viewController
animated:YES];
}
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
if (error != nil) {
// Authentication failed (perhaps the user denied access, or closed the
// window before granting access)
NSLog(#"Authentication error: %#", error);
NSData *responseData = [[error userInfo] objectForKey:#"data"]; //
kGTMHTTPFetcherStatusDataKey
if ([responseData length] > 0) {
// show the body of the server's authentication failure response
// NSString *str = [[NSString alloc] initWithData:responseData
// encoding:NSUTF8StringEncoding];
// NSLog(#"%#", str);
}
// self.auth = nil;
} else {
// NSString *authCode = [NSString alloc]in;
NSMutableURLRequest * request;
request = [[NSMutableURLRequest alloc] initWithURL:[NSURL
URLWithString:#"http://api.kliqmobile.com/v1/tokens"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60] ;
NSLog(#"%#",auth);
NSLog(#"ho gya success %# :::: %# :::: %#", auth.accessToken,
auth.refreshToken, auth.code);
NSMutableURLRequest * response;
NSError * error;
request.URL = [NSURL URLWithString:#"http://api.kliqmobile.com/v1/tokens"];
NSString *post = [NSString stringWithFormat:#"
{\"token\":\"%#\",\"secret\":\"%#\",\"service\":\"%#\",\"handle\":\"%#\"}",
auth.accessToken,auth.code,#"google",nil];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
error = nil;
response = nil;
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request
delegate:self];
[connection start];
}
I have implemented the NSURLConnection delegtes method and data is printing well like this
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
NSMutableURLRequest * response;
NSError * error;
NSLog(#"Did Receive Data %#", [[NSString alloc]initWithData:data
encoding:NSUTF8StringEncoding]);
NSMutableURLRequest * requestContacts;
requestContacts = [[NSMutableURLRequest alloc] initWithURL:[NSURL
URLWithString:#"http://api.kliqmobile.com/v1/contacts"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60] ;
[requestContacts setHTTPMethod:#"GET"];
[requestContacts setAllHTTPHeaderFields:headers];
error = nil;
response = nil;
NSData* data1 = [NSURLConnection sendSynchronousRequest:requestContacts
returningResponse:&response error:&error];
NSLog(#"WE GET THE REQUIRED TOKAN DATA %# :: %# :: %#", [[NSString alloc]
initWithData:data1 encoding: NSASCIIStringEncoding], error ,response);
}
but after that my app get crashed and it is giving following error;
[NSHTTPURLResponse release]: message sent to deallocated instance 0xcb51070.
please suggest me how to do this.
A couple of thoughts:
What is the intent of your didReceiveData method? There are a bunch of issues here:
You really shouldn't be doing a synchronous network request in the middle of a NSURLConnectionDataDelegate method.
You shouldn't be doing synchronous requests at all, but rather do them asynchronously.
What is the connection between receiving data and your creation of this new request? You're not using the data in the request, so why do it here?
The typical pattern is:
The didReceiveResponse should instantiate a NSMutableData object in some class property.
The only function of didReceiveData should be to append the received data to the NSMutableData. Note, this method may be called multiple times before all the data is received.
In connectionDidFinishLoading, you should initiate any next steps that you take upon successful completion of the request. If you wanted to do start another asynchronous network request when the initial request is done, do that here.
In didFailWithError, you obviously handle any failure of the connection.
When you call connectionWithRequest, you should not use the start method. Only use start when you use initWithRequest:delegate:startImmediately: with NO for the startImmediately parameter. Otherwise the connection starts automatically for you and you're only starting it a second time.
Unrelated to your original question, but your creation of post string cannot be right. You're missing a parameter value. Even better, rather than creating JSON manually, use NSDictionary and then use NSJSONSerialization to make the NSData object containing the JSON from this dictionary. That's much safer:
NSDictionary *params = #{#"token" : auth.accessToken,
#"secret" : auth.code,
#"service" : #"google",
#"handle" : #""};
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
Clearly, supply whatever you need for the handle value.
A tangential process-related observation, but I'm wondering if you're taking advantage of everything Xcode offers. For example, your declaration of response as a NSMutableURLRequest but then using that as a parameter to sendSynchronousRequest should have generated a compiler warning. The same thing is true with your stringWithFormat for your post string (my third point). That should have generated a warning, too.
Neither of these are immediately relevant, but I wonder if you are failing to heed any other compile-time warnings. These warnings are your best friend when writing robust code and I would recommend resolving all of them. To go a step further, you should also run the project through the static analyzer ("Analyze" on "Product" menu, or shift+command+B), and resolve anything it points out, too.

Fetching an access token for youtube api iOS "Error" : "invalid_request"

I'm trying to get an access token for a youtube app for iOS. Here's the relevant code I have been using from my viewDidLoad method:
mAuth = [[GTMOAuth2Authentication alloc]init];
[mAuth setClientID:#"<MY CLIENT ID>"];
[mAuth setClientSecret:#"<MY CLIENT SECRET>"];
[mAuth setRedirectURI:#"urn:ietf:wg:oauth:2.0:oob"];
[mAuth setScope:#"https://gdata.youtube.com"];
[self.web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?client_id=%#&redirect_uri=%#&scope=%#&response_type=code&access_type=offline", mAuth.clientID, mAuth.redirectURI, mAuth.scope]]]];
After this is called, the user has to grant access to their account, then I retrieve the auth code from the resulting page in the following code:
NSString *string = [self.web stringByEvaluatingJavaScriptFromString:#"document.title"];
if([string rangeOfString:#"Success"].location != NSNotFound){
NSLog(#"This is the code page");
NSString *importantCode = [[string componentsSeparatedByString:#"="] objectAtIndex:1];
NSLog(#"%#", importantCode);
if([self.defaults objectForKey:#"super important code"] == nil){
[self.defaults setObject:importantCode forKey:#"super important code"];
[self.defaults synchronize];
NSString *post = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=code", [self.defaults objectForKey:#"super important code"], mAuth.clientID, mAuth.clientSecret, mAuth.redirectURI];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"]]];
[request setHTTPMethod:#"POST"]; [request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[self.web loadRequest:request];
}
[timer invalidate];
}
After that, I should be given the access token in response to my POST request, but instead I get a page that simply says:
{
"error" : "invalid_request"
}
Does anyone (see where I went wrong)/(know how to retrieve the access token)?
I’d be interested in knowing what the HTTP status code is... I suspect ”invalid_request” means 400, which almost always means there’s some irritating stupid little error in the way you composed your authent URI. I don’t know enough iOS/ObcJ to tell if you’ve properly URLescaped any funny characters in any of the parameter values, but it’s worth checking. Or a typo in one of the values, or an extra newline creeping in or something?
It was as simple as this, I had set the grant_type parameter to 'code' when it should have been 'authorisation_code' if you are reading this and you are using the youtube api, don't make the same mistake. If you're reading this and you're sending a POST request in general, this error "invalid_request" means that either you skipped one of the parameters you should have added, or you added it incorrectly.

iOS POST request parameters random crash when connecting to Zend server

This question is related to this other one: Zend getParameters not returning what is in url route
The problem I'm facing is that, randomly, the Zend server does not get the parameters that are in the route, causing the login of my app crash. I.e., sometimes when printing the getParams(); function I get the user email as following:
Array (
[email] = user#email.com
(...)
)
This works fine, but some other times I get this:
Array (
[user#email.com] = 2.874983 //Longitude
(...)
)
Causing the crash of the login action.
This could be a fault in the server side or in the client side. I've put an NSLog to print the NSMutableURLRequest each time the server gets called, and I've seen that the request url is always well formed. Maybe this is a coincidence, I don't know, but sometimes trying to solve this issue I've changed the request code and it was temporarily fixed. But then, after some requests, the error was back.
The following snippet represents the code I'm using to connect to the server:
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self._url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSMutableString *values = nil;
if ( params ) {
NSDictionary *parameters = params;
values = [[NSMutableString alloc] init];
for ( NSString* key in parameters ) {
NSMutableString *value = [[NSMutableString alloc] init];
[value appendString:key];
[value appendString:#"="];
[value appendString:[self urlEncodeValue:[parameters valueForKey:key]]];
[value appendString:#"&"];
[values appendString:value];
}
}
NSData *postData = [values dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLenght = [NSString stringWithFormat:#"%d", [postData length]];
if ( cookies ) {
NSDictionary *cooks = cookies;
for ( NSString* cookie in cooks) {
NSMutableString *ck = [[NSMutableString alloc] initWithString:cookie];
[ck appendString:#"="];
[ck appendString:[cooks valueForKey:cookie]];
[theRequest addValue:ck forHTTPHeaderField:#"Cookie"];
}
}
[theRequest setHTTPMethod:self._method];
if ( values ) {
[theRequest setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPBody: postData];
[theRequest setValue:postLenght forHTTPHeaderField:#"Content-Length"];
}
// create the connection with the request
// and start loading the data
NSLog(#"%#", theRequest);
NSURLConnection *theConnection =[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
Another important thing is that the login sends both latitude and longitude values, and it seems that it's crashing when some of those values changes.
I've solved this problem and I've posted the solution here: Zend getParameters not returning what is in url route
It was a memcached configuration problem, nothing to do with the iOS client application.

Send request to server iOS

I am trying to figure out how to send data to the server but currently without any progress.
What I know
On the server I have got some php script that return me data in response
for example with this URL: http://test.com/mobile_api/register
this script get next parameters:
id
name
info
time
so the string which I need looking like below
http://test.com/mobile_api/register?id=1000&name=alex&info=1.0&time=10000
What is best way to send this is string on the server
Now I'm trying to use ASIHTTPRequest. Can anybody send an example how to create correct request with my parameters.
This sample code should help you
-(void)sendRequest
{
int userId=10, time=10000;
NSString *name = #"ABC";
float info = 1.0;
NSString *urlString = [NSString stringWithFormat:#"http://test.com/mobile_api/register?id=%d&name=%#&info=%f&time=%d",userId,name,info,time];
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
//You need to add ASIHTTPRequestDelegate in header(.h) file
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
// Use when fetching binary data
NSData *responseData = [request responseData];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}

Resources