iOS/Restkit application design - ios

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).

Related

Upload image from iOS to Django

I need help getting a basic understanding of uploading a file to a Django view via a post request. This is the Django form I'd like to upload the image to:
https://domfa.de/upload_profile/
This is the views.py code for this exact Django view URL:
def profile_picture(request):
if request.POST:
form = UserProfileForm(request.POST, request.FILES)
obj = form.save(commit=False)
obj.user_id = request.user.id
obj.profile_picture = obj.profile_picture
obj.save()
return render_to_response('profile.html', args, RequestContext(request))
else:
formNew = UserProfileForm()
args = {}
args.update(csrf(request))
args['uid'] = request.user.id
args['form'] = formNew
return render_to_response('profile.html', args, RequestContext(request))
And the actual form for this is extremely simple with just a single field for the actual profile picture:
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('profile_picture',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
So the Django side works great, I'm always able to upload an image successfully as long as I'm logged in. I'm stuck though however on how to POST an image to this extremely simple Django view, I've already logged in to the Django server as a user using a separate NSUrl request:
UIImage *picture = [UIImage imageNamed:#"myFile.png"];
NSData *imageData = UIImagePNGRepresentation(picture);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL
URLWithString:#"https://domfa.de/upload_profile/"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"image/png" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody:imageData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"%#", returnData);
So assuming all the Django code works, which it does, what's wrong with my objective-c code which does the actual image uploading?
And also, how could I get response messages from the server in the NSLog so I could better know why the server won't accept a file POST request?
Getting feedback what is going on when sending a HTTP request from iOS
The problem is that you are not passing in a pointer to a NSURLResponse object which you could examine after the request was made.
NSURLResponse *response;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
Now you can examine the output by looking at the object.
Why is it not uploading?
There are several issues with your approach: You are using django's forms API which is OK, but there are two pitfalls in your code:
CSRF You are not setting the the CSRF value correctly when submitting the form. You can workaround it by first accessing your form with a GET request, just like a browser would do it, then get the CSRF token from the cookies which the server set and then sending a POST request including the retrieved CSRF token. See also CSRF handling in AJAX requests
Data encoding You are not sending form data back to the view, but raw data instead. This will not work this way. You would have to send proper POST form data. You could do it manually or use ASIHTTPRequest which abstracts the cumbersome handling of multipart/form-data.
I would rethink the design decision to use a form to programatically upload a picture. Why not use something more like a REST API for this? There are great frameworks for implementing a clean REST API in django (e.g. http://tastypieapi.org/).
Maybe looking at the API description of Twitter and app.net could help inspiring you how to build this.

iOS app http post/get request

I need some tutorial, how to use HTTP POST (or GET) request from my iOS app. I want to send one string to my server and than write it to database. I've found this piece of code:
NSString *post = #"key1=val1";
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];
I add it to UIAction button, but it don't send anything to my server. On my server, I have a PHP script that takes that "key1" from post and than it write it to db.
<?
$postr = $_POST["key1"];
$con0 = mysql_connect("server","db","pass");
mysql_select_db("table", $con0);
mysql_set_charset('utf8',$con0);
mysql_query("INSERT INTO tok (token) VALUES ('$postr')");
mysql_close();
?>
Can anybody tell me what I am doing wrong?
Look at AFnetworking and work through their api. Sending a post request using the api is very fast, and is what most apps use for web connectivity.
Also please dont be discouraged by sarcastic comments. You should tag iOS projects as iOS and not xcode (unless you actually need help with the actual program xcode). But I don't think it's productive to harrass everyone that comes in and makes this mistake. A more tactful way would be a personal message as opposed to a public retort
https://github.com/AFNetworking/AFNetworking
AFNetworking is a very powerful library that can help you to reduce the effort on create your HTTP requests, you can find several examples on how to use this library on its github page.
You may find this answer useful for your needs: AFNetworking Post Request

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