load MySQL results into UITableView (iPhone) - iphone

I am making an iphone app which needs to draw information directly form a MySQL database, however, I have no idea how to go about doing that. does anyone have any open source samples or walkthroughs on how to do this?
Thank!

You can you this API hosted on github.com .
https://github.com/gwdp/Obj-c-MySql
It's free and very well documented .

you can create an sqlite file from your database, and then import that file to your project.And access that sqlite file same as you fire sql query.See tutorials of accessing sqlite file.

I would look into the NSURLConnection documentation on how to load data from a remote server. Create a web service in your remote server that will return data in XML or JSON depending on the request sent from your app and have your app populate your cells using the returned data.
One naive approach is to send a request to a PHP page. You can write the request like this to post to your php page:
NSString* content = [#"value=getAll"];
NSURL* url = [NSURL URLWithString:#"http://www.url.com/pagetopost.php"];
NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[content dataUsingEncoding: NSASCIIStringEncoding]];
Your PHP would have code that will fetch from the MySQL DB depending on the POST value sent in and return the data as JSON.
Then you will have to handle the response and maybe put that in an array that will be populated to your table view cells.

Related

How to initiate webservice request that expects JSON payload

I am JSON newbie and can't find any material on how to simulate JSON payload request.
My ultimate goal is to be able to build an objective-c iOS app that will handle these request-response. I am aware of ASIHttprequest framework and the request-response mechanism it works around.
However right now I have a webservice api which expects various json payloads and also provides response in json format. Here is an example:
Example URL:
https://mywebServiceURL/api/ApiKey/user/create
The ContentType header = “application/json”.
Payload: The PUT payload is a JSON dictionary, containing the following keyvalue pairs:
email
screenName
User’s screen name.
password
passwordConfirm
phoneNumber (optional)
User’s phone number (optional)
picture A png file (64x64), encoded as a Base64 string (optional)
Now my questions:
1 - how do I simulate this normally (outside ios, just for the sake of testing)? I searched google but can't find exactly what I need, I got curl.exe but it gives me same as what a browser gives, like method not allowed etc. But that's not the only thing I want. I want to play with various requests, supply values and take the api for a ride for sometime before I know how it really works for PUT, GET, POST etc.
2 - what is the best way to incorporate such stuff into iOS? I already have ASIHttp for web requests and JSONKit for JSON handling included in my project.
I have done this kind of stuff but with xml responses, get requests. JSON I am working for the first time. Just a pointer to an example stuff like this would be a great help.
There are several Chrome extensions, such as Advanced REST client or REST Console, that you can use to simulate REST calls. These are very quick and easy to install into your browser and will allow you to construct requests and view the response.
I recommend using the open source iOS networking library AFNetworking. This library has built in support for REST calls and JSON parsing. It is very easy to get up and running, and is very powerful if you need more advanced features.
Hope this helps.
Jsut to add upon Andy's suggestions as I have used similar kind of things in one of my recent app.
Used Chrome extension Poster for testing REST calls.
Used ASIHttpRequest for handling async queries.
Sample code snippet
//dictionaryData contains the login user details
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryData options:kNilOptions error:nil];
NSString *jsonString = [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]autorelease];
//Handling ASI requests
ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:uri];
[request addRequestHeader:#"Content-Type" value:#"application/json"];
[request addRequestHeader:#"Accept" value:#"application/json"];
[request appendPostData:[jsonData dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
[ASIHTTPRequest setDefaultTimeOutSeconds:30];
request.delegate = self;
[request startAsynchronous];

Sending information to server using URLs

I'm currently working with a PHP developer to set up some server-side code, however, I'm not sure how to send the server API information to be stored in a database. He has asked me to send it in a url like this: exampleserver.com/register?deviceToken=[deviceToken]&otherstuff[otherStuff]. I have no problem with creating the URL string, my issue is actually doing something with it. I know this is a pretty stupid question, but I'm pretty new to Objective-C let alone communicating with servers! I have pulled information from servers using NSURLRequest and AFJSONRequestOperation before. Is it the same idea or are we no longer doing Requests? I've seen the word Post around a couple of times, but I'm unsure if this is what I'm after. Any help clearing this up would be really appreciated. Also, whatever the solution, I need it to be asynchronous!
Thanks for the help,
Regards,
Mike
This works for me:
NSURL *aURL = [NSURL URLWithString:#"http://www.google.co.uk/search?hl=en&q=hello%20world"];
NSURLRequest *aURLRequest = [NSURLRequest requestWithURL:aURL];
[NSURLConnection sendAsynchronousRequest:aURLRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
NSLog(#"response=%#", response);
NSLog(#"data=%#", data);
NSLog(#"error=%#", error);
}];
The URL you show has data tacked onto the end of the URL, which is normally done with a http GET operation, the "normal" method. Just asking for the page at that URL is enough to send the data to the server. An http POST operation is typically used to send form data to a server, where the pairs like deviceToken=<deviceToken> are transferred in the body of the message rather than the URL. The advantage of that is typically that the body will be encrypted if the connection is https:, so the data stays secure. But for a simple insecure transaction, using a GET with the parameters in the URL is fine. There's a description of a POST transaction at iOS: how to perform a HTTP POST request?
NSURLRequest still works and is fine. If you want a more powerful library that handles post, get, put etc. and can work asynchronously and link directly to core data, I recommend RestKit (https://github.com/RestKit/RestKit).
For more on NSURL, see my answer here: NSURLConnection delegate method

Retrieving response from a php url in iphone

I have created an api. Lets say this is my php url
"http://xxxxxxx/game/game.php?validate=yes&email=myEmail#mars.com"
The response of this query is either 1 0r 0. It validates the email if it exists in db or not. I have been searching but failing till now, How am i suppose to send it to server. By NS URL or I have to use NSURLConnection. How in turn I can read the response.
Best Regards
NSString *response = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://xxxxxxx/game/game.php?validate=yes&email=myEmail#mars.com"]];
Bible, Old Testament.
Bible, New Testament.
Edit: so the response is XML? Right. (No, not right, you should really consider using JSON, but anyways...) You can use the NSXMLParserClass to get back the response in this case. Especially have a look at its - initWithContentsOfURL: method.

how to use ASIHTTPRequest Class for post request to upload a text file to server?

I am working on an upload code which will upload the file to the server, which is successfully working
now what I need as fallows:
started with an example-->suppose I have a file named file.txt, whose size is 30MB, when I read the contents of the file it will give me all the 30MB it contains. In the sendSynchronousRequest method I want to give request upto 10mb of data and aging calling the same thing unless it reaches at the last point of file. (in brief I want to use a loop to send the request part by part to the server
to solve the purpose i read form http://allseeing-i.com/ASIHTTPRequest/How-to-use and Included the ASIHTTPRequest in to my project after inclusion i want to do the same , that will accept a block of data (even via a POST) then append that block of data to a file. It seems to me that you need some kind of client side app that will take a file and break it up into chunks, then send it to your web service one chunk at a time.
My problems:
-how to sent a Post Request from ASIHTTPRequest with a chunk of data?
-do i need to change the PHP ?
Can any one post a piece of code for both php and ASIHTTPRequest so that i can take a reference from their.
Thank you guys for your continuos support .
If you use a form in the website, it would be easier to use ASIFormDataRequest instead of the standard ASIHTTPRequest. The specific details are here: Using ASIFormDataRequest
Essentially, you just create the form fields in the website and reference them when you create the request. If you have any text fields in your form you use the
[request setPostValue:#"Your value" forKey:#"form key"];
The file should be sent through the path using
[request setFile:#"filepath to needed file" forKey:#"form key"];
If you want you can also send it asynchronously and use the delegate methods for tracking the progress of the upload.
I hope this helps.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"Ben" forKey:#"first_name"];
[request setPostValue:#"Copsey" forKey:#"last_name"];
[request setFile:#"/Users/ben/Desktop/ben.jpg" forKey:#"photo"];
From ASIHTTPRequest documentation
You can refer to the following link available on the stack overflow:
NSURLConnection to upload file asynchonrously?

what is the difference between post and get request for asihttprequest?

I am wondering what the difference between Get and Post with asihttprequest library..
Is this a GET?
- (IBAction)sendHttpsRequest
{
//Set request address
NSMutableString *databaseURL = [[NSMutableString alloc] initWithString:#"https://142.198.16.35"];
//call ASIHTTP delegates (Used to connect to database)
NSURL *url = [NSURL URLWithString:databaseURL];
//This sets up all other request
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}
is a post when you try to set elements say within a php document? any examples would be awesome!
http://www.cs.tut.fi/~jkorpela/forms/methods.html
An HTTP GET is a request from the client to the server, asking for a resource.
An HTTP POST is an upload of data (form information, image data, whatever) from the client to the server.
What you have there is an HTTP POST.
-EDIT:
Per http://allseeing-i.com/ASIHTTPRequest/:
ASIFormDataRequest
A subclass of ASIHTTPRequest that handles x-www-form-urlencoded and multipart/form-data posts. It makes POSTing data and files easy, but you do not need to add this to your project if you want to manage POST data yourself or don’t need to POST data at all.
My bad, this one was a POST, not a GET. The rest of my answer was valid, though :)
That is a POST request, which is the default for ASIFormDataRequest. The difference is the same as it would be in a normal HTTP request. You can read about that here if you don't already know.
In general, if you are just downloading a web page and do not need to send any variables to the server, a GET request is sufficient. If you want to send variables in your request, often times a POST request is the way to go since it is a bit more secure and less transparent.