Trouble posting to database, from iOS app - ios

I'm having a problem updating my database from an iOS app...
Sql statements
<?php
// Create connection
$con=mysqli_connect("server_name","user_name","user_code","table_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'table.name'
$sql = "SELECT * table_name";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
$sql = "INSERT INTO table_name (column_name) VALUES('1')";
// Close connections
mysqli_close($result);
mysqli_close($con);
?>
My iOS code
for (Tickets *items in _feedItems){
if ([resultText.text isEqual:(id) items.ticketNumber]) {
status.text = #"Match found";
//Contacting database------------------------------
NSString *strURL = [NSString stringWithFormat:#"TicketDate=%#", items.ticketDate];
NSData *postData = [strURL dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://webservice.com"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-
Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
//Contacting database END-------------------------------------------
break;
}else {
status.text = #"Match not found";
}
}
I get a Connection Succesful from the NSLog but there is nothing getting updated in my database.
I'm trying to manually type in a ticket number with an app, and if that matches with a ticket in the database (it works), then I want the the ticketDate to change from 0 to 1.
But it does not change :/

You are not calling
[conn start];
to have your request effectively sent. I.e.:
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];
You should also be aware that the request will be sent asynchronously, this means that you will not get the response right after calling start. What you should do, if you want to stay with an async connection, is implement a data delegate, and at least its – connection:didReceiveData:, – connectionDidFinishLoading:, and connection:didFailLoadingWithError: methods.
Alternatively, you might consider sending the request synchronously, i.e., just replacing
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
with:
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
But this kind os request will block your app UI, unless you send them on a background thread.

In the database I have a row with a ticketNumber and ticketDate. If the number typed into my app is the same as a ticketNumber in my database, then i want the same row's ticketDate to change from 0 to 1.

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;

How can we pass multiple urls in collectionview

I am creating a social networking application, in that am using Horizontal collection view cell displaying for post.
my requirements are,
I have 10 differnt url api but in that see (initWithFormat:#"acc_id=104 && method=getHomeContents && start_limit=0" ) if i increase start_limit then i can get another post details.
I need to pass this data at the time of viewdidload
but how can get this post data at the time of viewdidload and collectionView numberOfItemsInSection how can i declare this suggest any ideas
if(indexPath.item==3)
{
NSString *post = [[NSString alloc] initWithFormat:#"acc_id=104 && method=getHomeContents && start_limit=0"];
// NSLog(#"%# ",post);
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http:vblive/APIFiles/Services.php?"]]];
[request setHTTPMethod:#"POST"];
// NSLog(#"request is %#",request);
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
_myConnection2 = [[NSURLConnection alloc]initWithRequest:request delegate:self];
// NSLog(#"%#",conn);
if(_myConnection2)
{
NSLog(#"connction sucess");
}
else
{
NSLog(#"unsucess");
}
}
Thanks
Sravan
Try some thing like this
1. create a tag or you can use variable like
NSString *startLimitValue;
2. Then Assign the startLimit value in View did load or where ever you want like
startLimitValue=#"one"
3 then use indexPath to assign Start limit value to different collection view cell
You can use Tags for specific item also
then dynamically set the no of items using Count method
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
if(check your condtion)
{
return [yourObject count];
}
else
if(check your conditon)
{
return [yourObject count];
}
}
I guess start limit has the integer value.
I would suggest for each view give the tag in collection view as 0 or 1 or 2....as the start limit values.
Then when user tap on item then using initWithFormat format the string using tag value of the item.

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.

How to call a function of web service for login? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a Web-Service API in PHP and i want to do login using this api in my ios application.
if (isset($_POST['tag']) && $_POST['tag'] != '')
{
// Get tag
$tag = $_POST['tag'];
// Include Database handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0); // check for tag type
if ($tag == 'login')
{
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password']; // check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false)
{
// user found // echo json with success = 1
$response["success"] = 1;
$response["user"]["fname"] = $user["firstname"];
$response["user"]["lname"] = $user["lastname"];
$response["user"]["email"] = $user["email"];
$response["user"]["uname"] = $user["username"];
$response["user"]["uid"] = $user["unique_id"];
$response["user"]["created_at"] = $user["created_at"];
echo json_encode($response);
}
else
{
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
}
else
{
echo "Digitalnet API";
}
This Web-Service checks for the database query to match the email and password.
Now I have made the connection with the web service and it is returning me the response Digitalnet Api.
In the button event
- (IBAction)btnSignIn:(id)sender {
if( ([txtUserEmail.text isEqualToString:#""]) || ([txtUserPassword.text isEqualToString:#""]))
{
[self showErrorAlert];
}
NSString *post = [[NSString alloc] initWithFormat:#"email==%# AND password==%#",self.txtUserEmail.text,self.txtUserPassword.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"http://localhost/ColorPicker/index.php"]; NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; NSLog(#"Login response: is %#",str); //getting response
else if(str != nil)
{
ColorPickerViewController *cpvc =[[ColorPickerViewController alloc] init];
[self.navigationController pushViewController:cpvc animated:YES];
}
else
{ NSLog(#"some thing went wrong");
}
}
What should I do to make login with this web-service so that the request is being sent from the application on button click, and the Api Validates the Request's with email and password and then after the user is authenticated it will allowed to move to the next screen/view.
NOTE: The Api is included with the class 'include/DB_Functions.php' which will check the user validation with mysql db so please don't be confused with the Web-Service I just need to know the logic on IPHONE.
You say, you are getting response from web- service. That means it is working fine.
I think there is some problem sending post parameters from url to the web-service.
Try something like this(just a piece of code. you need to modify it accordingly):
NSString * parameters = [NSString stringWithFormat:#"email=%#&password=%#",self.txtUserEmail.text,self.txtUserPassword.text];
[_mutableRequest setHTTPMethod:#"POST"];
NSData *requestData = [NSData dataWithBytes:[parameters UTF8String] length:[parameters length]];
[_mutableRequest setHTTPBody:requestData];
// then hit the connection using NSURLConnection

How to resolve multiple NSURLconnection with separated data

I have 2 separate NSURLConnection.
NSURLConnection * connection_users;
NSURLConnection * connection_cards;
Then i created the data with parameters, etc. and I finish with:
connection_users = [[NSURLConnection alloc] initWithRequest: url_request_users delegate: self startImmediately: YES];
In the delegate method:
- (void) connection: (NSURLConnection *) connection didReceiveData: (NSData *) data
i Checked if the connection is for the connection_users:
if (connection == connection_users) / / do something as an example:
NSDictionary * json_response = [NSJSONSerialization JSONObjectWithData: data options: kNilOptions error: & error];
Use the "data" that came from the method.
Before closing the "if" I create the next connection to "connection_cards", doing the same things
Out of "if" but within the same method I do another "if" to "connection_cards" and do the same thing with JSONObjectWithData.
Only the "data" that comes from the method is always of the first connection.
What is happening differently? For the second connection was initiated then you should receive the "data" corresponding.
Already canceled the first connection before starting the second to see if solved, but no.
How to obtain the "data" correct for second connection?
PS: if you need more codes, please let me know.
EDITED:
As Wain ask
url_request_users = [[NSMutableURLRequest alloc] init];
NSMutableString *post_users = [[NSMutableString alloc] init];
[post_users appendFormat:#"%#", [NSString stringWithFormat:#"email=%#&senha=%#",
[[alert textFieldAtIndex:0] text],
senha_md5]];
[url_request_users setURL:[NSURL URLWithString:WBS_USERS_RECOVER]];
[url_request_users addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[url_request_users setHTTPMethod:#"POST"];
[url_request_users setHTTPBody:[post_users dataUsingEncoding:NSUTF8StringEncoding]];
connection_users = [[NSURLConnection alloc] initWithRequest:url_request_users delegate:self startImmediately:YES];
For n different connections you will need n different NSMutableData which contains result of related NSURLConnection. A basic example for your question;
NSMutableData *data_users;
NSMutableData *data_cards;
Than on your didRecieveData;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (connection == connection_users) {
[data_users appendData:data];
} else if ( connection == connection_cards) {
[data_cards appendData:data];
}
}
This way you can keep track of your data's and connection's seperately. Remember to clear leftovers for your datas when your connection is over
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (connection == connection_users) {
// use data from data_users
NSDictionary * json_response = [NSJSONSerialization JSONObjectWithData:[data_users copy] options: kNilOptions error: & error];
data_users = [[NSMutableData alloc] init]; // clear data users
}
// do the same for cards connection
}
Last thing to do is to allocate your data before you call this function;
url_request_users = [[NSMutableURLRequest alloc] init];
NSMutableString *post_users = [[NSMutableString alloc] init];
[post_users appendFormat:#"%#", [NSString stringWithFormat:#"email=%#&senha=%#",
[[alert textFieldAtIndex:0] text],
senha_md5]];
[url_request_users setURL:[NSURL URLWithString:WBS_USERS_RECOVER]];
[url_request_users addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[url_request_users setHTTPMethod:#"POST"];
[url_request_users setHTTPBody:[post_users dataUsingEncoding:NSUTF8StringEncoding]];
data_users = [[NSMutableData alloc] init]; // add this line in your code
connection_users = [[NSURLConnection alloc] initWithRequest:url_request_users delegate:self startImmediately:YES];

Resources