Using a REST API and iPhone/Objective-C [duplicate] - iphone

been wrestling with this for some time. I am trying to access a REST api on my iphone and came across the ASIHTTP framework that would assist me. So i did something like
//call sites, so we can confirm username and password and site/sites
NSURL *url = [NSURL URLWithString: urlbase];
ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
[request setUsername:#"doronkatz%40xx.com" ];
[request setPassword:#"xxx"];
Where urlbase is a url to a REST site.
Now, a developer has told me there might be an issue or bug with this framework, and its not passing headers correctly. Is there another way of testing or accessing with authentication a network REST location?

I would recommend checking out RestKit: http://restkit.org/ It provides an excellent API for accessing RESTful web services and representing the remote resources as local objects, including persisting them to Core Data. HTTP authentication is supported out of the box.

I'm new to iOS development and I've been battling with some of the big frameworks listed on this page for the past month or so. It has been a nightmare. I'd honestly recommend you just stick to the basics and do it yourself using AFNetworking or Apple's own NSURLConnection.
One of the libraries listed is no longer maintained. Another underwent huge code-breaking API changes recently and now half of the tutorials describing its use no longer work. Others are massively bloated.
It's easier than you'd think. Some resources that helped me:
http://blog.strikeiron.com/bid/63338/Integrate-a-REST-API-into-an-iPhone-App-in-less-than-15-minutes
http://www.slideshare.net/gillygize/connecting-to-a-rest-api-in-ios
The examples on the AFNetworking homepage alone may get you 80% of the way there.
UPDATE: The Mantle Framework (open sourced by Github Inc.) is well-designed and easy to use. It handles object mapping: converting a JSON NSDictionary to your own custom Objective-C model classes. It handles default cases sensibly and it's pretty easy to roll your own value transformers, e.g. from string to NSURL or string to your custom enum.

I have a couple of apps using a framework called Objective Resource which provides a wrapper for accessing remote REST based api's. It is aimed primarily at Ruby on Rails based applications so it's XML/JSON parsing may be tuned to handle some Rails defaults but it is worth looking at. It supports http basic authentication by default.

Just stumbled on this question - you might find LRResty pretty interesting as it uses NSOperation, blocks etc., see: GitHub for source (MIT license). I'm experimenting with it now - it has a sample app too.

I've used ASIHTTP in two apps so far and have had no problems.
Looks like you're doing HTTP Basic Auth with the remote site. Try hitting the same REST URL from a standard browser and pass the params you need down to it. It should prompt you for username/password. If it makes it through, then at least you know the server-side is set up to handle requests. If it doesn't, then you need to have a talk with the dev.
The next thing to try is put a Mac-based network sniffer and see what headers are going back and forth. Any of HTTPScoop, Wireshark, or Charles should work. Run the sniffer as a network proxy then run your app in the simulator and watch what goes across. Try it again with the browser. Once you see the differences, you can use the addRequestHeader method on ASIHTTPRequest to add any specific headers the server expects.

Related

iPhone Noob, needs suggestions on how to communicate with the internets via iOS

we were asked to develop an iphone app like the one in the figure.
The problem is: we have no experience in IOS development.
For the basic part I can handle the learning curve, but i need suggestions, best practices on the UIKit model and controls.
This is a newspaper app.
The accordion control shows/hides content based on categories retrieved by an ASP .NET CMS on which we have no control.
I can suggest to the CMS holder to develop a couple of web services (WCF) but i'm not sure how to interface iOS with MS technology.
Furthermore, i have the idea that simple aspx that returns XML/JSON data will be easier to call, and support, but slightly less secure.
So, suggestions? Tutorials?
If you like to use JSON and a very good HTTP-request-framework I have two links for you. Both sites contain various tutorials on how to use them.
json-framework
ASIHTTPRequest
Concerning the request and delegate stuff: For a start, I would skip the delegate part and use a synchronized HTTP request called in a thread (you'll see what that is on the second website). That makes the response handling a lot easier for the start. But I personally think, that using an asynchronous request is not a must. It's just nicer, if the architecture allows it. In my application, it wasn't realizable without lots of code overhead.
You want to output an XML feed in "plist" format (look it up, its simple theres lots of info on it).
Then you can do:
NSArray *plistContents = [NSArray arrayWithContentsOfURL:[NSURL URLWithString:#"http://theinternet.com/pathToMyPlist.asp"]];
That will get all the output into an array.
Some other resources you may find interesting/useful include NSURLRequest and NSURLConnection. For the latter you will have to learn about delegate methods and such - its complicated, but its incredibly useful information.
We did several applications here using XML parsing like what you're suggesting at the end of your question. If you are concerned about security, you can implement handshaking or other security measures over that.
EDIT: XML parsing done using NSURLConnection to gather the content and NSXMLParser/NSXMLParserDelegate to do the actual parsing.
EDIT2: There is an official sample, called SeismicXML from Apple. It should get you started with iPhone XML parsing and data downloading.

How do I access a REST API on the iPhone?

So I'm brand new to rest's API and have never used an API ever before. I'm ok with Objective-C and Cocoa Touch but just have no clue where to start when accessing the API and how to in general. Can someone help me get started with some code that will access titles in rest or just how to access a REST API in general with authentication. Thanks.
Try http://allseeing-i.com/ASIHTTPRequest/
Good framework!
Take a look at RestKit: http://restkit.org/
It features a high level object mapping framework that can turn remote RESTful responses back into local objects declaratively, handling all the parsing and mapping for you.
http://github.com/mirek/NSMutableDictionary-REST.framework is easy to use.
To get REST as dictionary from GitHub API as an example:
NSString *url = #"http://github.com/api/v2/xml/user/search/mirek";
[NSMutableDictionary dictionaryWithRESTContentsOfURL: url];
To post:
[myDict postRESTWithURL: #"http://localhost:3000/my-rest"];
It supports sync/async, intuitive array conversions, url encoded and multipart posts (you can send images and other files).

iPhone application talking to a web service, the basics

We have an iPhone application created by an external consultancy that we're planning to add card payment facilities to in a subsequent release.
We plan to host a service ourselves in order to process the payment stuff, with SSL encryption. We have in-house expertese for all of this apart from the (contracted out) iPhone bit.
Are there any specific gotchas that we should be aware of that concern designing web services for iPhones?
We'll be writing the web service in C# 3.5.
JSON data format is better to be converted into NSArray or NSDictionary objects. It's easier and faster to be parsed.
So, specifically for the iPhone, it's a lot better to consume JSON data. Unless if there's some technical complexity that JSON is unable to handle.
Check YAJL:
http://github.com/lloyd/yajl
There are Objective-C wrapper/implementations by gabriel in github and by MGTwitterEngine.
TouchJSON is another code that's simpler than yajl. You can convert JSON string into NSDictionary or NSArray object in 2 lines of code. But, it maybe slower.
I'm not sure there are really any special considerations. The iPhone should be able to communicate with most types of webservice.
I worked on an iPhone app that communicated to a RESTful webservice written in Java.
I imagine it's pretty straightforward across the board - there are plenty of libraries for parsing/generating XML or JSON formatted messages, the iPhone can handle HTTP authentication, HTTPS, caching, etc.
It's just down to your iPhone developer to get it right :)
For SOAP based web services I strongly suggest that you try gSOAP. This library does not support Objective-C, however it supports C and C++ and is certainly the most complete open source project to access SOAP based web service; it also outperforms all of the other libraries.
For Objective-C you may want to try wsdl2objc, but I am not sure if it provides support for SSL/TLS (gSOAP does).
Finally, REST based web services are easily handled using ASIHTTPRequest.

Code for syncing the iPhone with REST-servers

is there any open source code for syncing an iPhone
with a server (preferably REST)?
Found nothing on github and google code.
Regards...
I have been working with a project called ObjectiveResource (Github project here: http://github.com/yfactorial/objectiveresource/tree/master), which is focused mainly on the communication layer between your iphone models and a REST based web service. It is targeted at rails applications but should work with any REST api. Part of that project is a more sync oriented solution that is still in early development, but which has been discussed quite a bit lately in the objective resource google group at http://groups.google.com/group/objectiveresource?hl=en.
I highly recommend objective resource, I've been using it along with sqlitepersistenobjects to handle sync on my iphone project.
I suggest using the excellent ASIHTTPRequest source from All-Seeing Interactive: http://allseeing-i.com/ASIHTTPRequest. I'm doing this, and so are several released iPhone apps, so you can be sure the code is pretty solid.
This is a wrapper around the CFNetwork API that makes some of the more tedious aspects of communicating with web servers easier. It is written in Objective-C and works in both Mac OS X and iPhone applications.
It is suitable for performing basic HTTP requests and interacting with REST-based services (GET / POST / PUT / DELETE). The ASIFormDataRequest subclass makes it easy to submit POST data and files using multipart/form-data.
I've used Adrian Kosmaczewski's iPhone Rest Wrapper with success. See also this SO question.
I would recommend checking out RestKit: http://restkit.org/ It provides an excellent API for accessing RESTful web services and representing the remote resources as local objects, including persisting them to Core Data.

How can I connect iPhone and web service and get XML data?

I know how to connect to web server using an iPhone but now I have to connect the iPhone to a web service. I don't know how to do it and there is no demo or class available online.
Does anyone have any ideas?
You might find this tutorial, called Intro to SOAP Web Services useful. He shows how to package a request, send it to a web service, and read the response.
If you need some help with XML parsing, there is the TouchXML library which will give you a nice xml "document" to work with. Just be cautious of memory usage.
If you have to parse large XML message this tutorial about libxml and xmlreader in Cocoa will show you how to parse XML with the lower-level event-style parsers.
I've created an open source application for iPhone OS 3.0 that shows how to use REST & SOAP services in iPhone application, using XML (using 8 different iPhone libraries), SOAP, JSON (using SBJSON and TouchJSON), YAML, Protocol Buffers (Google serialization format) and even CSV from a PHP sample app (included in the project).
http://github.com/akosma/iPhoneWebServicesClient
The project is modular enough to support many other formats and libraries in the future.
The following presentation in SlideShare shows my findings in terms of performance, ease of implementation and payload characteristics:
http://www.slideshare.net/akosma/web-services-3439269
You can use these 2 lines which return the response of your HTTP request. You don't need any configuration. This code is usefull if you try to access a PHP scritp for example. After you just have to parse your result.
NSURL *URL=[[NSURL alloc] initWithString:stringForURL];
NSString *results = [[NSString alloc] initWithContentsOfURL :URL];
In my opinion, you have two options :
Use a third party library. You can try wsdl2objc. It didn't work for me, but it is under active development so it improves every day.
Use a raw HTTP connection and handle every request/response. This is the way I followed. It is hard, so I'd also like to know a better approach.