Connect xcode to mysql through php - mysql

I am using the following code to insert in mysql table from Xcode app via php,
-(void)insertDetails:(NSString *)userEmail loginType:(int)type{
login_email = userEmail;
NSString *strUrl = [NSString stringWithFormat:#"http://localhost/insertLoginDetails.php?userEmail=%#&login_type=%d",userEmail,type];
NSData *dataUrl = [NSData dataWithContentsOfURL:[NSURL URLWithString:strUrl]];
NSString *strResult = [[NSString alloc] initWithData:dataUrl encoding:NSUTF8StringEncoding];
NSLog(#"%#",strResult);
}
This uses the GET method, can anyone please tell me how to use the POST method for the above process.
Thanks in advance.
Regards,
Neha

Make use of NSUrlconnection to call the webservice
Use requestWithURL:(NSURL *)theURL
If you need to specify a POST request with HTTP headers make use of NSMutableURLRequest with these methods
-(void)setHTTPMethod:(NSString *)method
-(void)setHTTPBody:(NSData *)data
-(void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field

There are lots of tutorial avaiable about NSURLConnection. like Fetching data with GET,POST methods by using NSURLConnection
Fetching data with GET,POST methods by using NSURLConnection have expalined how to fetch data from server synchronously and Asynchronously.

Related

Xcode - Create timeout for NSURL

I use NSURL to load some things from an MySQL Database. Sometimes this is very slow and the app stops running because the Database is not answering.
I thought I could make a timeout, so after e.g. 3 seconds, the app stops loading the NSURL and tries again or does something else like an UIAlertView.
Please help me!
Jannes
PS: I use this code to load these things from the Database:
-(void) loadSomething {
NSError *error;
NSString *urlString = #"http://someip/App/somefile.txt";
NSURL *url = [NSURL URLWithString:urlString];
#try {
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
}
#catch (NSException *exception) {
NSLog(#"Error");
}
Your request is a synchronous request and this type of request freezes the ui, you should use an asynchronous request to prevent the freeze.
Here is a tutorial on request asynch / synch that should help you.
Otherwise perhaps think to use the framework " AFNETWorking " it greatly simplifies the use of NSURLConnection and NSURLRequest

I'm making an IOS application, how do I make the application send me the UDID of the device its on?

Im currently developing and IOS application, For security purposes I would like to know how I can make the app send the device "UDID" to a server.
So basically I need to know how to make the device "fetch" the udid and then take the udid and send it to a server as a "request".
If the UDID is "registered" in the MYSQL database, then the server will send back a confirmation.
Besides finding out how to get the udid, I may need additional help setting up the mysql database :$
Thanks!
You can get the UUID of an iOS device using: CFUUIDRef udid = CFUUIDCreate(NULL);
NSString *udidString = (NSString *) CFUUIDCreateString(NULL, udid);
(Apple dont like you to use the UDID).
As far as posting it to a server, I suggest using a JSON post method, and recording the success. A good JSON library is SBJson which can be found here. Youll need to create a HTTP post, get the response data, and use SBJson library to parse the response.
EDIT: OR instead of SBJson, as Carbonic acid kindly pointed out, you can use NSJSONSerialization. Also, as pointed out by Naz Mir, new UUID method used.
Edit:
[[[UIDevice currentDevice] identifierForVendor] UUIDString] is not deprecated as I stated. Please go through the links below for information.
Getting UDID as stated above NSString *uuididentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; is deprecated and Apple no longer allows it. If your aim is to uniquely identify a device you can use SecureUDID or OpenUDID
I have used OpenUDID sometime back in one of our apps and using it is as simple as -
#import "OpenUDID.h"
[OpenUDID setOptOut:NO];
self.openUDID = [OpenUDID value];
Once you have the required value sending it to the server is trivial. You can use iOS networking library like AFNetworking to send and receive data. For example,
#import "AFHTTPRequestOperation.h"
NSURL *url = [NSURL URLWithString:#"Your sever URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *postString = [NSString stringWithFormat:#"&UDID=%#", self.
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
AFHTTPRequestOperation *httpOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *httpOperation, id responseObject) {
//handle server response here
NSLog(#"%#", [httpOperation responseString]); //this contains the servers response
}failure:^(AFHTTPRequestOperation *httpOperation, NSError *error) {
//handle server errors here
NSLog(#"error: %#", [httpOperation error]);
}];

iOS App Development - Database

I am currently working on an iOS application, and need to store data in a database(not locally). I have done some research on Core Data, but I want to store the data on a web server. Any suggestions?
Thanks
You'd have to do that through some API like a RESTful service. I would do something like this:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://my.website.com/restService"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[[NSString stringWithString:#"value1=test&value2=test2"] dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *urlResponse = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
If you want to store data somewhere on server and you dont have server -you can use one fo the following:
1) iCloud
2) Parse - You can create database on parse.com and use that database directly with Parse API. look at https://parse.com/docs/index for more detail.

Modify a repo to get JSON asynchronously

I'm working on an iPhone app that needs to load data from my server in JSON or XML format. Since the app is free, I get huge amount of data and I get crash when launching app due to the long time when loading the data. So I understand that I should not get "all" the JSON at once but I have to load the data "pagened" [ little by little ] ..
I found this project that suits well my needs but can't get succes to modify it to my need :
https://github.com/nmondollot/NMPaginator
The project tooks Twitter api as a data source, what if I need to deal with a simple php file that returns JSON formatted data?
nb: I tried to contact the project developer after I tried to modify, but didn't get answer until now.
Thanks.
The easiest solution could be to just download the data in another thread. This can be done in many ways but one way to do it is by using grand central dispatch (GCD).
Something like this
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
NSURL *url = [NSURL URLWithString:#"Your_URL"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:req
queue:[NSOperationQueue currentQueue]
completionHandler:
^(NSURLResponse *res, NSData *data, NSError *err) {
// Convert the data to appropriate object
NSString* myString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//You would probably deserialize the json here
//self.tableViewArray = serialiedObjects;
 
dispatch_async(dispatch_get_main_queue(), ^{
//Reload table view
[self.tableView reloadData];
});
}];
});

Xcode - Show database table value in text field

I am running a phpmyadmin database and have made a table with 3 columns. Username, Password and Age. In Xcode ive made a login app that uses the username and password to login with
NSString *strURL = [NSString stringWithformat:#"http://localhost/database/login.php?username=%#&password=%#", usernamefield.text, passwordtextfield.text];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
if ([strResult isEqualToString:#"1"])
This code works fine!
Is it then possible to show the third column in the database (AGE) in a text label when pressing login? so the Age of the user logged in will be displayed in a text label at the top bar of the app?
There's a lot that you could do to improve the security (not sending the password as a parameter of a GET request, it might (will) end up on some log somewhere unprotected), reliability (your script might not be the only thing that need to run on localhost) or the responsiveness (not doing a synchronous call) of that code.
But, starting with that code as a minimalistic starting point, you could configure your php script to respond with the age value and dispatch this value to a textfield/window title/whatever you want.
But then how to check if the user is correctly connected? Your script running on localhost could respond with bad authentication with a string.
For example:
NSString *strURL = [NSString stringWithformat:#"http://localhost/database/login.php?username=%#&password=%#", usernamefield.text, passwordtextfield.text];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
if ([strResult isEqualToString:#"auth_error"]){
// do something
} else {
[window setTitle:strResult]
}
But that's really a start.
After that, you might be interested to use JSON to answer the request and then read it with NSJSONSerialization, making your script a little more reliable and RESTful.