Connecting my iPad app to a SQL Server - ios

I have an iPad application that uses table view controllers to present lists of data. I want to connect these tables to data in a SQL Server. I have very little experience in this realm of programming and I am not sure where to begin. In the long run I'd like adding/editing/deleting data on the app to sync with the server as well. I understand that this is a very broad question, so I am mainly looking for suggestions to help me get started. I, for example, do not want to start researching and learning Core Data if it is not the framework that can accomplish my goal.
In short, how can I connect my application to a SQL Server so that I can access its data and sync it to a device? Any example code/walkthroughs would be much appreciated.

I am currently working in an iOS application that requires this same functionality. For mySQL database queries on the server, I am using server-side PHP scripts that can accept variables, such as the table name or database search term.
What I do is I make an HTTP GET request using objective-C's NSMutableURLRequest, then have the server process the request (in PHP), and then return the database query results to my application in JSON format. I use SBJsonParser to parse the returned data into an NSData, and then an NSArray object.
An example of making an HTTP request in Objective-C:
NSString *urlString = [NSString stringWithFormat:#"http://website.com/yourPHPScript.php?yourVariable=something"];
NSURL *url = [NSURL URLWithString: urlString];
NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] initWithURL:url];
/* set the data and http method */
[request1 setHTTPMethod:#"GET"];
[request1 setHTTPBody:nil];
/* Make the connection to the server with the http request */
[[NSURLConnection alloc] initWithRequest:request1
delegate:self];
There is more code that you need to add to actually respond to the request when it returns, and I can post an example of that if you would like.
I actually dont know if this is the best way to do this, but It has worked for me so far. It does require that you know PHP though, and I don't you if you have any experience with it.
UPDATE:
Here is some sample code showing how to respond to the request. In my case, since I am getting a JSON encoded response, I use the SBJsonParser to parse the response.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
/* This string contains the response data.
* At this point you can do whatever you want with it
*/
NSString *responseString = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
/* Here I parse the response JSON string into a native NSDictionary using an SBJsonParser */
SBJsonParser *parser = [[[SBJsonParser alloc] init] autorelease];
/* Parse the JSON into an NSDictionary */
NSDictionary *responseArr = [parser objectWithString:responseString];
/* Do whatever you want to do with the response */
/* Relsease the connection unless you want to re-use it */
[connection release];
}
Also add these methods, assuming you have an NSMUtableData instance variable titled receivedData.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}

I would not recommend connecting directly to a SQL server. You could, in theory, try to compile FreeTDS or unixODBC for iOS. I did not try it, but from my experience, at least FreeTDS should be fairly portable.
However, there are many other (and for most purposes better and easier) way of synchronizing data with a SQL Server. For example, you could use RestKit on the iPad side and a simple REST service on the SQL Server side. Or you could use OData which has a iOS library (which I just recently learned about, I have to admit).

Related

Why do i get authenticationchallenge with NSURLRequest when switching to HTTPS?

I've used NSMutableURLRequest for a long time to connect to my server.
In order to avoid double roadtrips, i set the usr/pwd right away in the header, like this:
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:HTTP_REQUEST_TIMEOUT];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", inUsr, inPwd];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [[authStr dataUsingEncoding:NSISOLatin1StringEncoding] base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
This has worked fine, the "willSendRequestForAuthenticationChallenge" is never called unless there is some error, so that method has always looked like:
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSDictionary *errorInfo = ((NSHTTPURLResponse *) challenge.failureResponse).allHeaderFields;
NSError *error; = [NSError errorWithDomain:#"httprequesthandler" code:WRONG_CREDENTIALS userInfo:errorInfo];
[delegate finishedWithErrors:error];
Now however, i'm using the same URL's as always, only "https" instead of "http", and suddenly this method is called every time.
I want my request to work as per normal, i.e. populate basic header and only one request to the server.
I'm not sure what i'm missing, so pointers would be much appreciated!
Using https as your scheme (or protocol) requests the connection be made securely, both by encrypting the data that is transferred as well as offering some information to you about the authenticity of the server you are connecting to.
The delegate method being invoked here (connection:willSendRequestForAuthenticationChallenge:), is not related to you authenticating yourself with the server, but the server authenticating itself with you. If you dig into the challenge object (NSURLAuthenticationChallenge), you can find the credentials the server is offering to let you know that it is the server you were actually trying to connect to, instead of an impostor.
Normally you don't need to use this method unless you want to validate the server in a way that goes beyond what the OS is doing for already.

iOS/Restkit application design

I'm currently developing an application for iOS that is backed by rails. For the communication between iOS and rails i use RESTkit framework since it takes away a lot of work!
I have some doubts on how to manage the code when it starts to grow! How do you design your applications when you use RESTKit? What kind of data layer do you provide to your controllers to perform different actions?
Thanks
I am not aware of what your goal is with the application that your building in.But to start with i suggest you to create your own custom class(for example: Click this link,which indeed accepts the request(might be POST/GET/PUT) that your making and throws you the details in json format.
On the server side,create the REST api(i prefer php) bridge such that you can able to access the server database.
To start with make login authentication test using POST method(i prefer this because its more secured).
After the login page,i assume you want to show the list of data related to rail,then use UITableView/UICollectionView/Custom GridView.It depends on your requirement.And use the asynchronous approach to send the request but below i haven't used that way ;-)
Example: For login authentication
NSString *post =[[NSString alloc] initWithFormat:#"userName=user&password=pwd"];
NSURL *url=[NSURL URLWithString:#"Your URL/authenticate"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];**
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if( theConnection )
{
receivedData = [NSMutableData data];
}
else
{
NSLog(#"theConnection is NULL");
}
NOTE: Always try to return the response in json format.
Q: WHY REST-API WITH JSON? WHY NOT SOAP?
==> Many enterprises are creating mobile applications for their internal staff, for their customers, or both. These applications need access to data, business rules, and business processes. For architectural and security reasons these applications are typically built to access remotes services that provide the data and functionality that are required by the users. That's why All of Yahoo's web services use REST.
-FASTER: REST is almost always going to be faster.
-LOW BANDWIDTH: REST is much more lightweight. For mobile devices even with low bandwidth & network, Restful service works well for mobile devices.
-LOW MEMORY CONSUMPTION: The important/must thing in the mobile devices is how we handle the memory when running our application. REST always uses less memory without any unwanted xml strings.
Concerning REST or SOAP, the last one is indeed really heavy for mobile platform and not so easy to implement. SOAP requires XML too and cannot be used with JSON. Whereas with REST you can use JSON or XML and easily implement it on mobiles with RESTKit (http://restkit.org/), for security we can use an SSL connection with HTTPS and a signed certificate.
Source: http://en.wikipedia.org/wiki/Representational_state_transfer
I believe that the information what i have given above is still not enough,you need to do a google a bit.(http://www.restapitutorial.com)
I usually prefer to create a singleton data controller which provides an API in terms of the model objects and the human understandable operation being performed (getPost, addCommentToPost, createPost, ...). This gives one place that controllers go to get data and means I don't need to pass the data controller around. It also means that all of the mappings are in one place and are isolated from the rest of the code (so when the server changes I don't need to change any code in the controllers, just the code which maps into the model objects).

What is the easiest way to make an HTTP GET request with IOS 5?

I am trying to send a suggestion from my app to a php file on my web server, I have tested the php script in my browser which sends an email to the user and stores the suggestion in my database, which all works fine.. And when running the following script I get a successful connection via IOS however i do not receive the results in my database..
NSString *post = [NSString stringWithFormat:#"http://blahblah.com/suggest.php?s=%#&n=%#&e=%#", suggestion, name, email];
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:post]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
NSLog(#"Connection establisted successfully");
} else {
NSLog(#"Connection failed.");
}
I have checked all the strings and encoded all spaces with %20 etc.. Can anyone see any glaringly obvious reason why my script won't work?
What is the easiest way to make a HTTP request from my app without opening safari?
You problem is that you're creating the connection, but are not sending the actual "connect" request. Instead of
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
try using this piece of code:
NSURLResponse* response = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil]
This is quick and dirty solution, but keep in mind that while this connection is in progress, your UI thread will appear to be frozen. The way around it is to use asynchronous connection method, which is a bit more complicated than the above. Search web for NSURLConnection send asynchronous request - the answer is there.

Any alternative to NSURL?

A client is pondering development of an iPhone and iPad app and has asked an odd question: Is there any way to send data from an iOS device to a server other than using NSURL?
I think you could try using a POST request
responseData = [[NSMutableData data] retain];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:#"http://www.domain.com/your/servlet"]];
NSString *params = [[NSString alloc] initWithFormat:#"foo=bar&key=value"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
That way the data would go inside the body of the request and not on the URL itself
The NSURL API isn't a way of getting data from a server. It's just a class for storing a URL. I suppose if you really want to avoid NSURL as much as possible, you could store URLs in an NSString, and then use appropriate APIs to convert it into an NSURL right before you use it.
To get data from a server, you would use either the NSURLSession API (modern) or NSURLConnection API (kind of crufty). Either is a fairly straightforward way to fetch data from an HTTP or HTTPS URL.
If you don't want to use either of those URL fetching APIs for some reason, you can write your own code using sockets or grab libcurl (MIT license) and link it into your app. Be aware that if you write your own socket code or use libcurl, assuming you're writing code for iOS, you'll need to occasionally use high-level APIs such as NSURL or CFHost to wake up the cellular radio.

How to write data to the web server from iPhone application?

I am looking forward for posting some data and information on the web server through my iPhone application. I am not getting the way to post data to the web server from iPhone sdk.
It depends in what way you want to send data to the web server. If you want to just use the HTTP POST method, there are (at least) two options. You can use a synchronous or an asynchronous NSURLRequest. If you only want to post data and do not need to wait for a response from the server, I strongly recommend the asynchronous one, because it does not block the user interface. I.e. it runs "in the background" and the user can go on using (that is interacting with) your app. Asynchronous requests use delegation to tell the app that a request was sent, cancelled, completed, etc. You can also get the response via delegate methods if needed.
Here is an example for an asynchronous HTTP POST request:
// define your form fields here:
NSString *content = #"field1=42&field2=Hello";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.example.com/form.php"]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[content dataUsingEncoding:NSISOLatin1StringEncoding]];
// generates an autoreleased NSURLConnection
[NSURLConnection connectionWithRequest:request delegate:self];
Please refer to the NSURLConnection Class Reference for details on the delegate methods.
You can also send a synchronous request after generating the request:
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
If you pass a NSURLResponse ** as returning response, you will find the server's response in the object that pointer points to. Keep in mind that the UI will block while the synchronous request is processed.

Resources