Everything is moving toward the cloud and unless you’re buildingcalculators,unit converters,or miniature golf score keepers youriPhone app needs to kNow how to get data from it. In this blog postI intend to demonstrate how to set up a simple server applicationand how to retrIEve data from it and post data to it using Cocoatouch. I have chosen to use PHP on the server sIDe because of it’ssimplicity and ubiquity,and because I’ve kNow it,somewhat. Youshould,however,be able to implement something similar using yourserver sIDe language of choice.
In many cases when you go to access remote data,you do so througha web service API. While services based on such technologIEs asSOAP or XML-RPC are standards that provIDe reasonable methods forretrIEving and updating data,REST seems to be the methodologygaining the most ground lately. For our purpose in this post Iwon’t get into great detail of how to implement a REST base webservice as,again,REST is not a specific implementation but rathera methodology. (Read up on it elsewhere if you don’t understanDWhat this means). However,I will talk about it brIEfly so that youcan get on the right path for doing your own RESTimplementation.
What Is The CloudIt seems that the term ‘cloud’ in this context has been around fora pretty long time,you can just think of it as,well,theInternet. If you access your data “in the cloud”,you are accessingyour data that is hosted on some server somewhere in the world. TheIDea behind it being that you can always access it no matter whereyou are. If your data is not “in the cloud”,then it is hostedlocally only and only accessible from that location.
Amazon.com among other technology leaders has helped to make thisMetaphor easIEr to understand. If you are familiar with Amazon S3(Simple Storage Service),then you kNow what it means to store yourdata “in the cloud”. Amazon has made it very cheap and very easy toaccess data that you store on their servers from anywhere in theworld. They provIDe a RESTful web service through which you cansecurely add,remove,and update data that you have stored there.If you have image or vIDeo assets,for example,that you find getaccessed a lot through your website,you may find that hostingthose files on S3 is cheaper than paying your own web host toprovIDe the banDWIDth and storage for them. This is a perfectexample of what cloud computing is and provIDes.
On a more generic level,cloud computing can mean setting up yourown service and provIDing access to resources or data in the samefashion. The difference in this case,is that you aremanaging it all on your own. Let’s take a look at how you might dothis.
Sending Arbitrary DataThe simplest PHP script can really teach you a great deal aboutwhat is going on between clIEnt and server. Remember that since weare depending on the Apache web server to serve up our PHPresponses a huge portion of the work is already done. We don’t haveto worry about low-level networking APIs and sockets. Instead wecan create a simple connection using a URL and the NSURLConnectionclass and we’re most of the way there. ConsIDer the following PHPcode sample.
123 | <?PHPprint $HTTP_RAW_POST_DATA;?> |
With one line of code (not including the Tags),we have justimplemented an echo server. Whatever you send to this script on theserver will be sent right back to you. You should understand thoughthat it is the
This really means that you can send anything you want as the bodyof the request and this script will store it in the$HTTP_RAW_POST_DATA and then
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:NSURL URLWithString:@"http://www.cimgf.com/testpost.PHP"]];[request sethttpMethod"POST"];[request setValue"text/xml" forhttpheaderFIEld"Content-type"]; Nsstring *xmlString = "<data><item>Item 1</item><item>Item 2</item></data>"; Nsstring stringWithFormat"%d",[xmlString length] forhttpheaderFIEld"Content-length"[request sethttpBody[xmlString dataUsingEnCoding:NSUTF8StringEnCodingNSURLConnection alloc] initWithRequest:request delegate:self];
When this request finishes,the same XML inthe
This example is just echoing back whatever we send,but if wewanted to get a little fancIEr,we Could load and parse the XMLwith the PHP XML parser and respond back to the clIEnt withsomething more useful.
What is also interesting about this code is that you can replacethe body of the request with any data type you’re interested inPOSTing to your server. If you post image data,youcan save that image data on the server sIDe using something likethis PHP script:
123456789<?PHP$handle = fopen("image.png", "wb"); // write binaryfwrite$handle$HTTP_RAW_POST_DATA; fclose$handle; "Received image file."?>
Keep in mind that this is very primitive and it does no sanitychecking on the body data. You would need to add that in order toimplement any real world server sIDe application. That being saID,these few lines of code demonstrate how you can send most any dataas the request body and process it on the server sIDe. OurObjective-C code from earlIEr modifIEd to support sending a PNGimage would look like this:
123456789101112131415NSData *imageData = UIImagePNGRepresentation[UIImage imagenamed"localimage.png"); "http://www.cimgf.com/testpostimage.PHP"]; // Not a real URL. "image/png" forhttpheaderFIEld[imageData length:imageData] initWithRequest:request delegate];
The request we are sending will be asynchronous so our UI will nothang,there is no accurate progress monitoring capability,so you would need to implement that if you want to have an IDea ofhow long it is going to take to post the image up to the webservice. See the section called
A lot of web applications began life as web forms in which the usercan obtain a List of records or a detail record based on input theuser provIDes. You can post form data programmatically using afairly trivial implementation not much different from the code wedemonstrated above. In the prevIoUs section we discussed that youcan send any arbitrary data to a web service or script by placingthat data in the body of the request. This is also true for sendingform data.
If you send form data,which is the default when you create anNSURLConnection object and use it to talk to your server,you willsee a string of key value pairs in the same format you wouldnormally see in a get request–somethinglike
ConsIDer the following BUG Reporter web form.
Yes,yes,I kNow–it’s beautiful. Looks like something you would seeCirca 1995. Stick with me here as I’m trying to keep things simple.The form takes two fIElds and just formats the input and respondsto the user with what the user entered. This same form can also besubmitted using code similar to what we’ve already shown. Here ishow you would programmatically post data to this form using andNSURLConnection/NSURLRequest.
1234567891011121314151617= ] initWithURL: NSURL URLWithString"http://www.cimgf.com/test/testform.PHP"*poststring "go=1&name=Bad Bad BUG&description=This BUG is really really super bad.";Nsstring stringWithFormat[poststring length[poststring dataUsingEnCoding];
Notice that we are passing a variablecalled
<HTML><head><Title>BUG Reporter</Title></head><body><h2>Fancy BUG Reporter</h2><hr />if (isset$_POST'go')){ @H_946_419@// Form was posted "User submitted BUG: ". 'name'] ": " 'description']}else// Form was not posted,display form?><form method="POST" action="<?PHP echo $PHP_SELF; ?>">BUG name:<br /><input type="text" name="name" maxlength="100" /><br />BUG Description:<br /><input type="text" name="description" maxlength="1000" size="80" /><br /><input type="submit" name="go" value="Add BUG"></form>}?></body></HTML>
When the request finishes posting to this form,you will have thesame HTML code in your data object as what you would see if youwere to vIEw the source in the actual web page after posting theform.
Simplifying Cloud Access Ben Copsey
Using the example I mentioned earlIEr of sending XML to our PHPecho script,the request would Now look like the following usingthe ASIhttpRequest object:
1234567ASIhttpRequest [ASIhttpRequest requestWithURL:url];"<data><item>Item 1</item><item>Item 2</item></data>";[request appendPostData[xmlString dataUsingEnCoding[request setDelegate[request setDIDFinishSelector:@selector(requestFinished[request setDIDFailSelector(requestFailed[request startAsynchronous];
Then you implement your delegate selector as in the following:
1234567891011- (voID) requestFinished(ASIhttpRequest *)request{ *response [request responseString]; // response contains the data returned from the server.}) requestFailedNSError *error [request error// Do something with the error.}
Similarly,if you want to submit data to a form like we dID earlIErusing the NSURLConnection/NSURLRequest combination,we can insteaduse the ASIFormDataRequest class.
1234567ASIFormDataRequest [ASIFormDataRequest requestWithURL[request setPostValue"1" forKey"go""Bad Bad BUG" forKey"name""This BUG is really really super bad." forKey"description"];
When this request completes,we will have the formatted HTML in theresponseString of the ASIhttpRequest object:
12345// response contains the HTML response from the form.}
I have come to prefer using ASIhttpRequest for network access,this is a matter of taste. It is a very clean and wellwritten library of classes,so I highly recommend it,but yourmileage may vary.
So What About REST? As I saID at the beginning,I’m not going to go into a lot ofdetail about how to set up a REST web service as implementation ofthe
Make heavyuse of mod_rewrite in your Apacheserver.
It also so happens to provIDe a great way to implement a REST webservice. Say you want to look up a BUG by it’s unique ID in a BUGtracker database. Your request would normally look like thishttp://www.cimgf.com/showBUG.PHP?ID=1234. The mod_rewrite moduleallows you to define rewrite rules that would change this URL tohttp://www.cimgf.com/BUGs/1234. The rule to do this is very simple.
12 | RewriteEngine OnRewriteRule ^BUGs/([[:alnum:]]+)$ /showBUG.PHP?ID= |
You just add this to the
Drive yourweb service with a scripted backend that connects to a commoditydatabase like MysqL.Sanity check all of the input you getfrom your user by looking for vulnerabilitIEs such as sql injectionattacks,but then insert the data into the database using standardsql calls. If you receive the data,as XML for example,you cansimply parse the XML into a DOM object and insert it from there.Better yet,use a (PHP) server sIDe module that converts from XMLto sql for you. @H_502_676@
Use aframework like Rails.
The down sIDe of this option for me is that I need to learn yetanother programming language,Ruby. While I’m getting around to it,it hasn’t been on the top of my priority List.
Use S3 forAssets.
Networking code has gotten much simpler to implement in recentyears,so accessing your resources in the cloud is a great solutionto many application development problems. There are some greattools out there these days regardless of whether you are develoPingthe clIEnt or the server. If you need to access the cloud,use thevarIoUs librarIEs available to you and keep your designs simple.Doing so will yIEld great results.
If you have some suggestions for how to implement REST web servicesfor iPhone apps,leave them in the comments section below. Rememberthat all comments are moderated,so if you don’t see your commentappear right away,just be patIEnt. We’ll approve it as soon aspossible. Until next time.
总结以上是内存溢出为你收集整理的ACCESSING THE CLOUD FROM COCOA TOUCH全部内容,希望文章能够帮你解决ACCESSING THE CLOUD FROM COCOA TOUCH所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)