UBER Ride Reminder Api Responding 403 Forbidden Response - objective-c

I am working on UBER ride reminders api.i am trying to post ride reminder using my server_token.passing required parameter but in response i am getting 403 forbidden response. my http request is as follows.
NSDictionary *event=#{
#"time":event_time,
#"name":event_name
};
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:reminder.reminder_time forKey:#"reminder_time"];
[params setValue:reminder.phone_number forKey:#"phone_number"];
[params setValue:event forKey:#"event"];
NSString *url=#"https://api.uber.com/v1.2/reminders?server_token=***our server token***";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSError *error=nil;
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
NSURLResponse *response = nil;
[request addValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSData *authData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(!error && authData!=NULL)
{
NSError *jsonError = nil;
NSDictionary *authDictionary = [NSJSONSerialization JSONObjectWithData:authData options:0 error:&jsonError];
if(!jsonError && authDictionary !=nil)
{
NSLog(#"got respose");
}
else
{
NSLog(#"Error retrieving access token %#", jsonError);
}
}
else
{
NSLog(#"Error in sending request for access token %#", error);
}
and response object I am getting from this is as follows
<NSHTTPURLResponse: 0x600000029100> { URL: https://api.uber.com/v1.2/reminders?server_token=wMV7Y-ssag45YXzyTYZnYD7lCDNiBBKaG6Botcv7 } { status code: 403, headers {
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Type" = "application/json";
Date = "Thu, 06 Apr 2017 07:39:50 GMT";
Server = nginx;
"Strict-Transport-Security" = "max-age=604800";
"Transfer-Encoding" = Identity;
"X-Content-Type-Options" = nosniff;
"X-Uber-App" = "uberex-nonsandbox, optimus, migrator-uberex-optimus";
"X-XSS-Protection" = "1; mode=block";
} }
and json response is this
{
code = forbidden;
message = Forbidden;
}

Related

uber api ride request getting 401 unautherized error response

I am trying to build mac osx application For UBER.I have completed all steps of Aouth2. I am successfully getting access_token. I am also able to retrieve user profile and history but while I am trying to post "ride request", I am getting 401 unauthorized error response.please help.Thank you In advance.
My code is as below.
**
//POST /v1/requests
NSString *sandBoxURL=#"https://sandbox-api.uber.com/v1";
NSString *url = [NSString stringWithFormat:#"%#/requests", sandBoxURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request addValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:[NSString stringWithFormat:#"Bearer %#", _accessToken] forHTTPHeaderField:#"Authorization"];
NSError *error = nil;
request.HTTPMethod = #"POST";
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
NSLog(#"Request for Product Request:%#",request);
[self performNetworkOperationWithRequest:request completionHandler:^(NSDictionary *requestDictionary, NSURLResponse *response, NSError *error)
{
NSLog(#"Response for Product Request:%#",response);
NSLog(#"Result:%#",requestDictionary);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300)
{ //OK
UberRequest *requestResult = [[UberRequest alloc] initWithDictionary:requestDictionary];
// handler(requestResult, response, error);
}
if (409 == httpResponse.statusCode) { //needs surge confirmation
NSLog(#"Surge Conflict");
}
else
{
NSLog(#"Error In response");
}
}];
**
And response I am getting is:
{ URL: https://sandbox-api.uber.com/v1/requests } { status code: 401, headers {
Connection = "keep-alive";
"Content-Length" = 83;
"Content-Type" = "application/json";
Date = "Mon, 07 Nov 2016 11:19:35 GMT";
Server = nginx;
"Strict-Transport-Security" = "max-age=0";
"X-Content-Type-Options" = nosniff;
"X-Uber-App" = "uberex-sandbox, migrator-uberex-sandbox-optimus";
"X-Uber-Missing-Scopes" = true;
"X-XSS-Protection" = "1; mode=block";
} }
Result:{
code = unauthorized;
message = "Requires at least one scope. Available scopes: ";
}
I got the solution. Problem Was With My Scope input.While requesting for token,even if the account you are login is of developer, we need put scopes properly. In my case I needed request scope in token.

How to fetch gmail Contacts in iOS application using google contacts api?

In my application we kept option to login through gmail. I have requirement to retrieve gmail contacts.
In the following method i am using auth object(once success) to fetch gmail contacts by creating request with url: "https://www.google.com/m8/feeds/contacts/default/full"
- (void)finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
if(!error) {
auth.clientID =myClientId;
auth.clientSecret =myClientSecret;
auth.scope= #"https://www.googleapis.com/auth/contacts.readonly";
NSString *urlStr = #"https://www.google.com/m8/feeds/contacts/default/full";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"3.0" forHTTPHeaderField:#"GData-Version"];
[auth authorizeRequest:request
completionHandler:^(NSError *error) {
NSString *output = nil;
if (error) {
output = [error description];
} else {
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (data) {
// API fetch succeeded :Here I am getti
output = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"%#",output);
} else {
// fetch failed
output = [error description];
}
}
}];
}
}
I'm getting client error(401). is there any thing i'm missing to my request.
The correct Scope is "https://www.google.com/m8/feeds"
In swift
class func getContactsFromUser() {
let urlStr = "https://www.google.com/m8/feeds/contacts/default/full"
let url = NSURL(string: urlStr);
var request = NSMutableURLRequest(URL: url!)
let appd = UIApplication.sharedApplication().delegate as! AppDelegate
let error: NSError!
appd.service.authorizer.authorizeRequest!(request, completionHandler: { (error) -> Void in
if error != nil {
println("error getting contacts is \(error.localizedDescription)")
} else {
let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error: nil)
if data != nil {
let stringResponse = NSString(data: data!, encoding: NSUTF8StringEncoding)
println("**** stringResponse **** \(stringResponse!)")
} else {
println("error 2 getting contacts is ")
}
}
})
}
In objective c
- (void)doAnAuthenticatedAPIFetch {
NSString *urlStr = #"https://www.google.com/m8/feeds/contacts/default/full";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[self.auth authorizeRequest:request
completionHandler:^(NSError *error) {
NSString *output = nil;
if (error) {
output = [error description];
} else {
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (data) {
// API fetch succeeded :Here I am getti
output = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
} else {
// fetch failed
output = [error description];
}
}
}];
}

Twitter api request using simple NSMutableURLRequest

I am trying to get a user latest twits , with a simple request but getting a code error 400 .
What am i missing with my request body ?
NSString *consumerKey = #"api key";
NSString *consumerSecret = #"api secret";
NSString *consumerKeyRFC1738 = [consumerKey stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
NSString *consumerSecretRFC1738 = [consumerSecret stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
NSString *concatKeySecret = [[consumerKeyRFC1738 stringByAppendingString:#":"] stringByAppendingString:consumerSecretRFC1738];
NSLog(#"-%#",concatKeySecret);
NSString *concatKeySecretBase64 = [[concatKeySecret dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:#"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2"]];
[request setHTTPMethod:#"POST"];
[request setValue:[#"Basic" stringByAppendingString:concatKeySecretBase64] forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
NSString *str = #"grant_type=client_credentials";
NSData *httpBody = [str dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:httpBody];
//NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest: request returningResponse: &response error: nil];
if ([response respondsToSelector:#selector(allHeaderFields)])
{
NSDictionary *dictionary = [response allHeaderFields];
NSLog(#"%#",dictionary);
NSLog(#"%#",response);
}
The respond giving me this :
<NSHTTPURLResponse: 0x10cc21ba0> { URL: https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2 } { status code: 400, headers {
"Content-Encoding" = gzip;
"Content-Length" = 86;
"Content-Type" = "application/json; charset=utf-8";
.....
....
If it suits your needs, I'd recommend you using SLRequest. Please note that this framework will ask for permission to use the user's account.
NSURL *showUserURL = [NSURL URLWithString:#"https://api.twitter.com/1.1/statuses/user_timeline.json"];
NSDictionary *parameters = #{ #"screen_name": #"thestrayhotdog" };
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodGET
URL:showUserURL
parameters:parameters];
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if (granted) {
NSArray * accounts = [accountStore accountsWithAccountType:accountType];
if ([accounts count]) {
ACAccount *twitterAccount = [accounts firstObject];
request.account = twitterAccount;
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *connectionError) {
NSLog(#"%#",[[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding]);
NSLog(#"Status code: %ld",(long)[urlResponse statusCode]);
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
if (error) {
// Handle error
}
// success;
}];
}
}
}];

Urban Airship - Send Push with NSURLConnection

I'm working on a simple prototype and need to test sending push notifications from one device to another.
I've emailed Urban Airship to turn on the "Allow Push From Device" for my application - and they did turn it on.
I'm trying to use NSURLConnection to send the push notification from the device.
This is my code:
- (void) test {
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://go.urbanairship.com/api/push"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSDictionary * push = #{#"device_tokens":#[#"<token>"], #"aps":#{#"alert":#"TEST", #"sound":#"default"}};
NSData * pushdata = [NSJSONSerialization dataWithJSONObject:push options:0 error:NULL];
[request setHTTPBody:pushdata];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void) connection:(NSURLConnection *) connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *) challenge {
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic]) {
NSURLCredential * credential = [[NSURLCredential alloc] initWithUser:#"<app key>" password:#"<app secret>" persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
[credential release];
}
}
- (void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
NSHTTPURLResponse * res = (NSHTTPURLResponse *) response;
NSLog(#"response: %#",res);
NSLog(#"res %i\n",res.statusCode);
}
Anyone else done this successfully?
Taking a look at Urban Airship's guide to troubleshooting HTTP status codes, and the documentation for the push API, my guess would be that you need to add a trailing slash to the URL:
[NSURL URLWithString:#"https://go.urbanairship.com/api/push/"]
Example Using the V3 API...
-(void)richPushNotification{
NSDictionary *push = #{
#"audience" : #{
#"device_token" : deviceToken
},
#"device_types" : #[ #"ios" ],
#"notification" : #{
#"ios" : #{
#"alert":Message,
#"sound":#"default",
#"badge":#"auto",
}
},
#"message": #{
#"title": Message,
#"body": #"<html><body><h1>blah blah</h1> etc...</html>",
#"content_type": #"text/html",
#"extra": #{
#"offer_id" : #"608f1f6c-8860-c617-a803-b187b491568e"
}
}
};
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://go.urbanairship.com/api/push/"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/vnd.urbanairship+json; version=3;" forHTTPHeaderField:#"Accept"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", appKey, appMasterSecret];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:push
options:0 // Pass 0 if you don't care about the readability of the generated string
error:NULL];
request.HTTPBody = jsonData;
[NSURLConnection connectionWithRequest:request delegate:self];
}
And The Response:
- (void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
NSHTTPURLResponse * res = (NSHTTPURLResponse *) response;
NSLog(#"response: %#",res);
NSLog(#"res %li\n",(long)res.statusCode);
if (res.statusCode == 202) {
//Show Alert Message Sent
}else{
//Handle Error
}
}

Simple http post example in Objective-C?

I have a php webpage that requires a login (userid & password). I have the user enter the information into the app just fine.. but I need an example on how to do a POST request to a website. The apple example on the support site is rather complicated showing a picture upload.. mine should be simpler.. I just want to post 2 lines of text..
Anyone have any good examples?
Alex
This is what I recently used, and it worked fine for me:
NSString *post = #"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://www.nowhere.com/sendFormHere.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
Originally taken from http://deusty.blogspot.com/2006/11/sending-http-get-and-post-from-cocoa.html, but that blog does not seem to exist anymore.
From Apple's Official Website :
// In body data for the 'application/x-www-form-urlencoded' content type,
// form fields are separated by an ampersand. Note the absence of a
// leading ampersand.
NSString *bodyData = #"name=Jane+Doe&address=123+Main+St";
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://www.apple.com"]];
// Set the request's content type to application/x-www-form-urlencoded
[postRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// Designate the request a POST request and specify its body data
[postRequest setHTTPMethod:#"POST"];
[postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];
// Initialize the NSURLConnection and proceed as described in
// Retrieving the Contents of a URL
From : code with chris
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://google.com"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = #"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
ASIHTTPRequest makes network communication really easy
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:#"Ben" forKey:#"names"];
[request addPostValue:#"George" forKey:#"names"];
[request addFile:#"/Users/ben/Desktop/ben.jpg" forKey:#"photos"];
[request addData:imageData withFileName:#"george.jpg" andContentType:#"image/jpeg" forKey:#"photos"];
You can do using two options:
Using NSURLConnection:
NSURL* URL = [NSURL URLWithString:#"http://www.example.com/path"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
// Form URL-Encoded Body
NSDictionary* bodyParameters = #{
#"username": #"reallyrambody",
#"password": #"123456"
};
request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];
// Connection
NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:nil];
[connection start];
/*
* Utils: Add this section before your class implementation
*/
/**
This creates a new query parameters string from the given NSDictionary. For
example, if the input is #{#"day":#"Tuesday", #"month":#"January"}, the output
string will be #"day=Tuesday&month=January".
#param queryParameters The input dictionary.
#return The created parameters string.
*/
static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
NSMutableArray* parts = [NSMutableArray array];
[queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
NSString *part = [NSString stringWithFormat: #"%#=%#",
[key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
[value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
];
[parts addObject:part];
}];
return [parts componentsJoinedByString: #"&"];
}
/**
Creates a new URL by adding the given query parameters.
#param URL The input URL.
#param queryParameters The query parameter dictionary to add.
#return A new NSURL.
*/
static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
NSString* URLString = [NSString stringWithFormat:#"%#?%#",
[URL absoluteString],
NSStringFromQueryParameters(queryParameters)
];
return [NSURL URLWithString:URLString];
}
Using NSURLSession
- (void)sendRequest:(id)sender
{
/* Configure session, choose between:
* defaultSessionConfiguration
* ephemeralSessionConfiguration
* backgroundSessionConfigurationWithIdentifier:
And set session-wide properties, such as: HTTPAdditionalHeaders,
HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
*/
NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
/* Create session, and optionally set a NSURLSessionDelegate. */
NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
/* Create the Request:
Token Duplicate (POST http://www.example.com/path)
*/
NSURL* URL = [NSURL URLWithString:#"http://www.example.com/path"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
// Form URL-Encoded Body
NSDictionary* bodyParameters = #{
#"username": #"reallyram",
#"password": #"123456"
};
request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];
/* Start a new Task */
NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil) {
// Success
NSLog(#"URL Session Task Succeeded: HTTP %ld", ((NSHTTPURLResponse*)response).statusCode);
}
else {
// Failure
NSLog(#"URL Session Task Failed: %#", [error localizedDescription]);
}
}];
[task resume];
}
/*
* Utils: Add this section before your class implementation
*/
/**
This creates a new query parameters string from the given NSDictionary. For
example, if the input is #{#"day":#"Tuesday", #"month":#"January"}, the output
string will be #"day=Tuesday&month=January".
#param queryParameters The input dictionary.
#return The created parameters string.
*/
static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
NSMutableArray* parts = [NSMutableArray array];
[queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
NSString *part = [NSString stringWithFormat: #"%#=%#",
[key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
[value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
];
[parts addObject:part];
}];
return [parts componentsJoinedByString: #"&"];
}
/**
Creates a new URL by adding the given query parameters.
#param URL The input URL.
#param queryParameters The query parameter dictionary to add.
#return A new NSURL.
*/
static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
NSString* URLString = [NSString stringWithFormat:#"%#?%#",
[URL absoluteString],
NSStringFromQueryParameters(queryParameters)
];
return [NSURL URLWithString:URLString];
}
I am a beginner in iPhone apps and I still have an issue although I followed the above advices. It looks like POST variables are not received by my server - not sure if it comes from php or objective-c code ...
the objective-c part (coded following Chris' protocol methodo)
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://example.php"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [NSString stringWithFormat:#"user_name=%#&password=%#", self.userNameField.text , self.passwordTextField.text];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
//NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSLog(#"Response: %#",[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
Below the php part :
if (isset($_POST['user_name'],$_POST['password']))
{
// Create connection
$con2=mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
// retrieve POST vars
$username = $_POST['user_name'];
$password = $_POST['password'];
$sql = "INSERT INTO myTable (user_name, password) VALUES ('$username', '$password')";
$retval = mysqli_query( $sql, $con2 );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysqli_close($con2);
}
}
else
{
echo "No data input in php";
}
I have been stuck the last days on this one.
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:#"name" forKey:#"email"];
[contentDictionary setValue:#"name" forKey:#"username"];
[contentDictionary setValue:#"name" forKey:#"password"];
[contentDictionary setValue:#"name" forKey:#"firstName"];
[contentDictionary setValue:#"name" forKey:#"lastName"];
NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonStr);
NSString *urlString = [NSString stringWithFormat:#"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:#"moinsam" password:#"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];
Thanks a lot it worked , please note I did a typo in php as it should be mysqli_query( $con2, $sql )
Here i'm adding sample code for http post print response and parsing as JSON if possible, it will handle everything async so your GUI will be refreshing just fine and will not freeze at all - which is important to notice.
//POST DATA
NSString *theBody = [NSString stringWithFormat:#"parameter=%#",YOUR_VAR_HERE];
NSData *bodyData = [theBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//URL CONFIG
NSString *serverURL = #"https://your-website-here.com";
NSString *downloadUrl = [NSString stringWithFormat:#"%#/your-friendly-url-here/json",serverURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: downloadUrl]];
//POST DATA SETUP
[request setHTTPMethod:#"POST"];
[request setHTTPBody:bodyData];
//DEBUG MESSAGE
NSLog(#"Trying to call ws %#",downloadUrl);
//EXEC CALL
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"Download Error:%#",error.description);
}
if (data) {
//
// THIS CODE IS FOR PRINTING THE RESPONSE
//
NSString *returnString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(#"Response:%#",returnString);
//PARSE JSON RESPONSE
NSDictionary *json_response = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
if ( json_response ) {
if ( [json_response isKindOfClass:[NSDictionary class]] ) {
// do dictionary things
for ( NSString *key in [json_response allKeys] ) {
NSLog(#"%#: %#", key, json_response[key]);
}
}
else if ( [json_response isKindOfClass:[NSArray class]] ) {
NSLog(#"%#",json_response);
}
}
else {
NSLog(#"Error serializing JSON: %#", error);
NSLog(#"RAW RESPONSE: %#",data);
NSString *returnString2 = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(#"Response:%#",returnString2);
}
}
}];
Hope this helps!