Consuming RESTful API with RESTframework

As explained in previous post, we’re going to demonstrate how RESTframework handles REST web services. I’ll be consuming a simple Django demo web service created in previous post, so either grab the sources or read the post and build it yourself. Assuming you have this service running on localhost, port 8000, we can continue.

First, download RESTframework from GitHub. With git client, simply type in terminal:

$ git clone git@github.com:ivasic/RESTframework.git

The quickest way to get RESTframework into your project is just including all the files from RFClasses  folder. RF does not have any external dependencies so building shouldn’t be a problem.

RFClasses

RFClasses

Now, we’ll also need JSONKit to parse API response and MBProgressHUD to show some progress. Grab both from GitHub and add to your project.

Fetching objects list

We’ll have 2 view controllers in our demo app. One will be a simple object list and the other one will be, even more simple, view controller for creating a new object. First, we’re going to show how to fetch the object list. We’ll need a GET request to /objects/ URL and we’ll need to parse the JSON array we get in response and show in the table view.

RFRequest* r = [RFRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8000/"] type:RFRequestMethodGet resourcePathComponents:@"objects", nil];
[MBProgressHUD showHUDAddedTo:self.view animated:YES].labelText = NSLocalizedString(@"Loading...", @"");
[RFService execRequest:r completion:^(RFResponse* response) {
	[MBProgressHUD hideHUDForView:self.view animated:YES];
 
	if (response.error) {
		UIAlertView* aiv = [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"") message:response.error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
		[aiv show];
		return;
	}
 
	self.dataSource = [response.dataValue objectFromJSONData];
	[self.tableView reloadData];
}];

So, what we’re doing in this code snippet is:

  • Creating a GET RFRequest with appropriate URL and resource path
  • Attaching MBProgressHUD to our view to show spinner progress
  • Executing RFRequest and defining the block to execute after RFResponse is received
  • Inside this block, we simply check for errors, parse the response, add to our tableView dataSource and reloading the table
You can see all this in action in the project sample attached to this blog post (at the bottom).

Creating new objects

Our view controller for creating new objects is responsible for creating POST requests to /objects/ URL. Again, very simple, you just need to do this:

RFRequest* r = [RFRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8000/"] type:RFRequestMethodPost resourcePathComponents:@"objects", @"", nil];
 
[r addParam:self.txtName.text forKey:@"name"];
[r addParam:self.lblDate.text forKey:@"date"];
 
[MBProgressHUD showHUDAddedTo:self.view animated:YES].labelText = NSLocalizedString(@"Submitting...", @"");
[RFService execRequest:r completion:^(RFResponse* response) {
	[MBProgressHUD hideHUDForView:self.view animated:YES];
 
	if (response.error) {
		UIAlertView* aiv = [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"") message:response.error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
		[aiv show];
		return;
	}
 
	UIAlertView* aiv = [[[UIAlertView alloc] initWithTitle:@"Success" message:@"Success" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
	[aiv show];
 
	[self.navigationController popViewControllerAnimated:YES];
}];

Similar to our previous snippet, but this time we also add some parameters to the request – name and date strings.

This is a brief overview with sample Xcode project of how RESTframework consumes RESTful web APIs. Questions welcomed via comments as usual.

 

Download project: RESTframework demo Xcode project download

REST framework for iOS is now Open Source

I have (finally) open sourced my RESTframework project on GitHub. It aims for simplicity of usage primarily. Querying RESTful web services is really easy now. Supported are iOS versions 4.0 and above and Mac OS 10.6 and above.

Feel free to fork & contribute!

RESTframework on GitHub

Calling JSON-RPC webservice in iOS

This topic is already covered in my post for consuming .NET web services in iOS but some questions were raised about passing arguments to the JSON-RPC methods that require them. In this short post I’ll just explain how to do just that.

Assume you have a few RPC methods that require some arguments like this.

[Jayrock.JsonRpc.JsonRpcMethod("HelloWorld")]
public string HelloWorld()
{
	return "Hello World!";
}
 
[Jayrock.JsonRpc.JsonRpcMethod("Echo")]
[Jayrock.JsonRpc.JsonRpcHelp("Simple echo method, takes string input and returns it")]
public string Echo(string input)
{
	return input;
}
 
[Jayrock.JsonRpc.JsonRpcMethod("EchoArray")]
[Jayrock.JsonRpc.JsonRpcHelp("Returns input arguments as an array of strings")]
public List EchoArray(string str1, string str2, string str3, string str4)
{
	List lst = new List();
	lst.Add(str1);
	lst.Add(str2);
	lst.Add(str3);
	lst.Add(str4);
 
	return lst;
}

Now, those “Echo” methods need some arguments passed to them and in this case I worked with strings but remember those args can be any primitive or complex but serializable types. So now that we have a working web service, we can query it from iOS. I’ll refer to my old example project which can be found here. The way it’s coded right now is to call the HelloWorld method without any arguments like this.

JSONRPCService* svc = [[JSONRPCService alloc] 
	initWithURL:[NSURL URLWithString:txtURL.text]];
svc.delegate = self;
 
[svc execMethod:@"HelloWorld" andParams:[NSArray array] withID:@"1"];

We need to notice that we passed an empty NSArray for params. This is because our HelloWorld doesn’t need any arguments. Easily enough, if you want to call the Echo method with a single param you’ll just add a string to an array and pass that array as execMethod:andParams:withID  2nd argument.

JSONRPCService* svc = [[JSONRPCService alloc] 
	initWithURL:[NSURL URLWithString:txtURL.text]];
svc.delegate = self;
 
[svc execMethod:@"Echo" andParams:[NSArray arrayWithObject:@"Echo Me!"] 
	withID:@"2"];

You can pass as many arguments as your method requires just stack ‘em up in an NSArray and make sure the argument order complies with the argument order of the web method.

JSONRPCService* svc = [[JSONRPCService alloc] 
	initWithURL:[NSURL URLWithString:txtURL.text]];
svc.delegate = self;
 
[svc execMethod:@"EchoArray" 
	andParams:[NSArray arrayWithObjects:@"1st arg", @"second arg", @"3rd arg", @"4th arg string", nil] 
	withID:@"3"];

Hope this helps!

JSON (de)serialization in iOS

A few people asked how to serialize and deserialize JSON data in iOS projects. I know it’s covered on almost every cocoa blog on this planet and basically very simple, but I’ll describe in this short post anyway. There are a couple JSON libraries for Objective-C that I know of, but the 2 most popular and widely used are TouchJSON and SBJSON. Both are very simple to use although TouchJSON developers seem to be a bit more active.

TouchJSON

You start by downloading TouchJSON files from GitHub and including them into your project.The next step would be importing header files CJSONDeserializer.h and/or #import “CJSONSerializer.h” and you’re good to code it. Very simple, like this:

Deserialization:

CJSONDeserializer *jsonDeserializer = [CJSONDeserializer deserializer];
NSError *error;
NSDictionary *resultsDictionary =
          [jsonDeserializer deserializeAsDictionary:jsonData error:&error];

Where jsonData is a string representation of your json data.

Serialization:

    NSString *jsonString = [[CJSONSerializer serializer]
               serializeObject:myDict];
    NSData *data = [jsonString dataUsingEncoding: NSUTF8StringEncoding];

where myDict is a NSDictionary you want to serialize. You can also use jsonString directly if you don’t need NSData…

SBJSON

Similar stuff here too, download the files and include them in your project. After that, a simple import of “JSON.h” in your implementation files enables you to parse JSON with ease.

Serialization

NSString* jsonString = [myDict JSONRepresentation];

That’s it. myDict is a NSDictionary* and with a single line you converted it to its JSON representation.
Deserialization

NSDictionary* result = [jsonString JSONValue];

Again, a single line and you converted your jsonString NSString object to Cocoa NSDictionary structure.

Which one should I choose?

Both are simple and fast, although I didn’t benchmark them. I’d suggest to try out both and make your pick, you certainly won’t go wrong with either. I personally go with SBJSON just for the sake of ultra simplicity.

 

BTW,  if you run into problems with linking JSON libraries (e.g. you’re already using some library that includes JSON library) make sure you read about this, you will find it helpful.

Simple UIView transitions animation using blocks in iOS 4

UIView’s sweet animation capabilities we were used to in pre-iOS 4 are now deprecated and Apple suggests we start using blocks which is far more convenient and simpler way of achieving the same thing. I’ll demonstrate how to make a simple UIView transition using new blocks based API vs using the old non-blocks way.

Our Goal

is to make an UIView curl up & down when adding and removing to a superview like shown below.

UIView page transition

UIView page transition

The Old Way – using +beginAnimations:context:

The old way code, using UIView’s class methods +beginAnimations:context: was simple enough and the code looks like below.

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown 
                                      forView:containerView cache:YES];
 
[containerView addSubview:subview];
 
[UIView commitAnimations];

Using blocks based API

Recommended usage of blocks API would change this code snippet to something like this.

[UIView transitionWithView:containerView duration:0.5
		options:UIViewAnimationOptionTransitionCurlDown
		animations:^ { [containerView addSubview:subview]; }
		completion:nil];

Now, this is all quite simple, nice & cute yet problems are likely to arise and you end up without animations. I’ve run into this myself, the problem is that one can easily make a mistake of passing options argument of the wrong type. The old way required UIViewAnimationTransition for transition argument while the blocks based API requires UIViewAnimationOptions for options argument. These are, obviously, completely different types but because they are both enum’s (int’s) you won’t get a compiler warning from XCode and if you mix them up you can spent quite some time trying to figure out why your animation doesn’t appear. Moreover, XCode’s autocomplete doesn’t even offer UIViewAnimationOptions when auto-completing. It tricked me and I was bumping my head why a perfectly good piece of code wouldn’t work.

All in all, make sure you don’t mix UIViewAnimationOptions with UIViewAnimationTransition when using transitionWithView:duration:options:animations:completion: method! I hope you enjoyed this mini tutorial for beginners, the XCode demonstration project is below.

UIView transitions animation XCode demo project.

Duplicate symbols when linking ObjectiveC static libraries

When you link a static library that’s using ObjectiveC categories, you usually have instructions from the developers to add -ObjC and -all_load linker flags which solve linking problems and prevent crashes. Now, if you happen to have the same categories or other objc symbols in your project that uses this static library you’ll get linker errors for duplicate symbols. The most common example for this is using touch JSON framework. I have this static library that uses it, and I also use it in my own code. I’m running into this linking problem every once in a while so I’m going to explain it here and provide a solution for fixing/avoiding it.

The Problem

Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 failed with exit code 1

ld: duplicate symbol _OBJC_METACLASS_$_SBJSON in /Users/ivan/Projects/MyApp/sources/Trunk/MyApp/libtest-simulator.a(SBJSON.o) and /Users/ivan/Projects/MyApp/sources/Trunk/MyApp/build/MyApp.build/Debug-iphonesimulator/MyApp.build/Objects-normal/i386/SBJSON.o

WARNING: I’ll be talking about problems with touch JSON library because this is the common problem. Solutions may not apply to other libraries although the principle is more-less the same. Be warned.

Scenario #1

“My project uses 1 static library and both this library and my project need JSON framework”.

Simplest solution that might work is to remove -ObjC and -all_load linker flags. When I say ‘might’, I mean that you need to be extra careful with this. If you do this, the static library you link will depend on JSON code from your project so if there’s, for example, a version mismatch you’ll run into serious problems.

LInker Flags in Xcode

Linker Flags

Scenario #2

“My project uses a static library which depends on JSON framework but this library also links other ObjectiveC static libraries. Both my project and this static library need JSON framework”

OR

“I cannot remove -ObjC and -all_load because I need to properly link categories inside a static library, but I also need to add JSON framework to my own project”

Now this is a specific scenario I ran into earlier. I wanted to use Three20 library which links several different ObjC libraries of its own so I definitely need -ObjC and -all_load flags otherwise my app crashes. On the other hand, I had another static library which uses JSON framework and adding this framework to my project causes duplicate symbols linker error.

The solution is simple again but you also need to be extremely careful. You leave those linker flags to properly link ObjC libraries but you don’t add JSON framework in your project. Instead you depend on JSON library linked with the static library you are using. You will, however, need to add header files in order to avoid compilation errors in your own code. Possible problem here is header files vs. compiled code in the static library mismatch. So you need to make sure that the JSON header files you’re using match the JSON code version linked with the static library. If you already imported JSON framework, just remove .m files in XCode from your target.

JSON framework xcode

JSON framework files

Bottomline

Obviously, these are some rare cases of linking problems however, JSON touch framework is a very popular framework and it’s not uncommon that some 3rd party libraries you want to use are built on top of it. My final advice is to understand the problem and why it happens, then you will be able to solve it one way or the other. Good luck!

6 Useful Objective C & Cocoa macros

Here are a few useful cocoa & cocoa touch macros that I’ve come across and thought I share here. Some of those I use regularly and some I just know about but you may find them useful.

Hex (HTML) color to UIColor macro

I found this macro a long time ago somewhere and I’m not sure what’s the original source, yet the Google search returned this blog so I’m going to give him the credit.

#define HEXCOLOR(c) [UIColor colorWithRed:((c>>24)&0xFF)/255.0
                                  green:((c>>16)&0xFF)/255.0
                                     blue:((c>>8)&0xFF)/255.0 \
                                    alpha:((c)&0xFF)/255.0]
//usage
UIColor* color = HEXCOLOR(0xff00ff00);

Enumerating collections macros

The following macro helps you with fast enumeration over collections, credit goes to Wincent.

#define WOEnumerate(collection, object)                                     \
for (id enumerator = [collection objectEnumerator],                         \
     selector = (id)@selector(nextObject),                                  \
     method = (id)[enumerator methodForSelector:(SEL)selector],             \
     object = enumerator ? ((IMP)method)(enumerator, (SEL)selector) : nil;  \
     object != nil;                                                         \
     object = ((IMP)method)(enumerator, (SEL)selector))
 
#define WOKeyEnumerate(collection, object)                                  \
for (id enumerator = [collection keyEnumerator],                            \
     selector = (id)@selector(nextObject),                                  \
     method = (id)[enumerator methodForSelector:(SEL)selector],             \
     object = enumerator ? ((IMP)method)(enumerator, (SEL)selector) : nil;  \
     object != nil;                                                         \
     object = ((IMP)method)(enumerator, (SEL)selector))

Logging macros

CMLog - use to extend NSLog functionality.

#define CMLog(format, ...) NSLog(@"%s:%@", __PRETTY_FUNCTION__,[NSString stringWithFormat:format, ## __VA_ARGS__]);
 
//usage
CMLog(@"My iPhone is an %@, v %@", [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion]);

MARK - method stamp macro, use to output class and method name.

#define MARK	CMLog(@"%s", __PRETTY_FUNCTION__);

Benchmarking macros

Use START_TIMER and END_TIMER to get the timing between these two calls.

#define START_TIMER NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
#define END_TIMER(msg) 	NSTimeInterval stop = [NSDate timeIntervalSinceReferenceDate]; CMLog([NSString stringWithFormat:@"%@ Time = %f", msg, stop-start]);
 
//usage example
- (NSData *)loadDataFromURL:(NSString *)dataURL
{
  START_TIMER;
  NSData *data = [self doSomeStuff:dataURL];
  END_TIMER(@"loadDataFromURL");
  return data;
}

Logging and benchmarking macros, courtesy of Stephan Burlot.

UIView frame (CGRect) macros

And for the end, here’s my own modest addition to the list. When developing an iPhone or iPad apps, you probably found yourself lots of times working with UIView frames, changing them etc… Often times I just change the UIView size or I just need to move it around the screen, reposition the view and each time I need to do CGRectMake etc… The following macros have helped me and saved me some typing.

#define width(a) a.frame.size.width
#define height(a) a.frame.size.height
#define top(a) a.frame.origin.y
#define left(a) a.frame.origin.x
#define FrameReposition(a,x,y) a.frame = CGRectMake(x, y, width(a), height(a))
#define FrameResize(a,w,h) a.frame = CGRectMake(left(a), top(a), w, h)

Obviously you can do the same for UIView ‘bounds’ instead of ‘frame’.

Handling layout on UIInterfaceOrientation change

In iOS version >= 3.0, it’s very simple to support interface orientation changes and layout your GUI elements accordingly. Support for landscape and portrait mode are very important for user experience and I think even essential on iPad. In this short text, we’ll cover several UIViewController instance methods that help dealing with UIInterfaceOrientation on iOS devices.

As an example, we can use the YouTube app that comes installed with iOS operating system. This great app shows how simple GUI provides perfect user experience in both landscape and portrait mode. Rotating your iPad makes it remove not needed GUI elements, at the same time unclutter the screen and resize visible controls to fit new layout.

YouTube iPad app

YouTube iPad app

In order to support a certain interface orientation, first you need to override the following method:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	//we want to support all orientations
    return YES;
}

Now that you enabled the interface rotation, you would want to implement the methods that inform you when the rotation (and rotation animation) starts and finishes. Those are:

  • willRotateToInterfaceOrientation:duration:
  • willAnimateRotationToInterfaceOrientation:duration:
  • didRotateFromInterfaceOrientation:

Simple enough – willRotateToInterfaceOrientation will be called just before the the device layout rotates, willAnimateRotationToInterfaceOrientation gets called inside animation block just before the animation of the rotation starts and finally didRotateFromInterfaceOrientation gets called once everything is finished and the rotation ended.

With these descriptions alone it’s easy to understand that your logic would be to:

  • Create views/controllers inside willRotateToInterfaceOrientation and add them to the layout
  • Modify view’s attributes (position, size etc…) inside willAnimateRotationToInterfaceOrientation
  • Clean up & remove not needed views inside didRotateFromInterfaceOrientation

Important thing to mention is that willAnimateRotationToInterfaceOrientation method is called inside an animation block so every animatable properties of your views you modify inside this method will be automatically animated. This is very neat, for example, if you just need to reposition and resize your views. You would just change pass desired CGRect as view’s frame and the change would be automatically animated for you when the device changes it’s orientation. to either portrait or landscape.

 - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
	if (UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
		previewLayout.frame = CGRectMake(695, 13, previewLayout.frame.size.width, previewLayout.frame.size.height);
	} else {
		previewLayout.frame = CGRectMake(413, 575, previewLayout.frame.size.width, previewLayout.frame.size.height);
	}
}

This example demonstrates view reposition only and as you can see the coordinates are hardcoded. I also used a macro UIInterfaceOrientationIsLandscape() which totally simplifies how you determine whether the interface orientation is portrait or landscape.

Besides mentioned methods for responding to view rotation events, there are another 3 that I’m just going to mention now and possibly cover in a future post. Basically they are triggered during animation and inform you about the first half of animation start/finish and the second half animation start. They are also called during animation block just like willAnimateRotationToInterfaceOrientation.

  • willAnimateFirstHalfOfRotationToInterfaceOrientation:duration:
  • didAnimateFirstHalfOfRotationToInterfaceOrientation:
  • willAnimateSecondHalfOfRotationFromInterfaceOrientation:duration:

Check out the Apple’s developer docs for more info.

To sum up – by responding to view rotation events using above mentioned methods, you can create rich user experience and make you app accessible in all orientations. Transitions from one orientation to another can also be enriched with nice animations in few lines of code so make sure you take advantage of that.

Showing network activity indicator in status bar

Showing network activity indicator in iOS device’s status bar is fairly simple job and can be done in 1 line of code. However, I’ve seen lots of apps with bugs in this area and moreover I see them every day. Reason for this is because few people actually pays attention to coordinate network activity indicator showing and hiding. Let’s see how do you show and hide the indicator.

	UIApplication* app = [UIApplication sharedApplication];
 
	//to show it, set it to YES
	app.networkActivityIndicatorVisible = YES;
 
	...
 
	//to hide it, set it to NO
	app.networkActivityIndicatorVisible = NO;
iPhone Status Bar

iPhone Status Bar w/ network activity indicator on

So, just this 1 line to either show or hide it. It’s that simple. But the problems may show up if you have multiple requests that release the indicator at different times so you get yourself a race condition. This problem can surely be fixed by using some of the concurrency techniques but I use a simpler method which includes request/release counter and updates the indicator accordingly.

First you need to find a suitable place for sending requests/releases to. I use app delegate as it’s singleton and can be accessed from any class but you can decide to use something else. You declare one integer ivar e.g. netActivityReqs and assign a property to it (optional). Now all you need is just these two methods and you’re done.

-(void) requestNetworkActivityIndicator {
	UIApplication* app = [UIApplication sharedApplication];
	app.networkActivityIndicatorVisible = YES;
 
	self.netActivityReqs++;
}
 
-(void) releaseNetworkActivityIndicator {
 
	self.netActivityReqs--;
	if(self.netActivityReqs <= 0)
	{
		UIApplication* app = [UIApplication sharedApplication];
		app.networkActivityIndicatorVisible = NO;
	}
 
	//failsafe
	if(self.netActivityReqs < 0)
		self.netActivityReqs = 0;
}

As you can see it’s extremely simple and straight-forward, you just need to pay attention to these details that may hurt user experience. You still, however, need to be careful to match your request and release calls as this idea only helps with preventing race conditions from multiple activity request calls but it can’t even your calls so you might end up with activity indicator spinning forever if you’re not careful.

Fetching emails from Gmail using Cocoa

I built this contact form for one website (my company’s) and at the time it was least expensive to just shoot out emails to a specific address with user’s messages and email addresses. Naturally, at one point I had to collect those emails & messages and use them so I ran into problem – what’s the easiest way to do that? Fortunately, our email server was GMail so I found a couple of ways to do it, avoid writing IMAP client and the easiest way for me was to use GMail’s built-in RSS feed and simply parse this feed to get what I want. In Cocoa, this should be simple enough but turned out not to be in my case.

Cocoa’s PubSub framework offers a nice way of subscribing to RSS feeds and it was ideal and simple for usage in this particular case. However, I just couldn’t get it to work with GMail’s authentication. I’ll explain below.

First I had to set up GMail account for easier access to the emails. Using search & filters, I found all emails that contained the info I needed and moved them to a separate temporary GMail label I created. At the same time I marked all emails as unread. This is very important because only unread emails appear in RSS feed and without this step, the feed for the label would appear empty.

Now the coding part. Ideally we would simply get PSClient and create a PSFeed, set username and password and traverse PSEntry objects in the feed. In theory, we’d do this:

PSClient *client = [PSClient applicationClient];
	NSURL    *url    = [NSURL URLWithString:@"https://mail.google.com/a/feed/atom/LABELNAME"];
	PSFeed   *feed   = [client feedWithURL:url];
 
	feed.login = txtEmail.stringValue;
	[feed setPassword:txtPass.stringValue];
 
	NSLog(@"Err: %@", feed.lastError);
 
	// Retrieve the entries as an unsorted enumerator
	NSEnumerator *entries = [feed entryEnumeratorSortedBy: nil];
	PSEntry *entry;
 
	// Go through each entry and get what we need
	while (entry = [entries nextObject]) {
		NSLog(@"%@", entry.summary.plainTextString);
	}

And this should work. However, it doesn’t. I always get this:

Err: Error Domain=NSURLErrorDomain Code=-1013 UserInfo=0x10017e450 "A username and password are required"

I still haven’t found the solution for this using PubSub framework. However I did manage to get the feed using plain HTTP NSConnection and simple authentication. So if anyone knows why this happens and/or knows how to solve it I would really appreciate if you notified me, thanks.

Anyway, back to our problem. Since this didn’t work, I simply tweaked it a bit and did a few things manually. I decided to use PSFeed’s initWithData:url: and pass the data (XML) manually from a NSTextField. First I opened the feed URL in my browser and logged in so I could actually see the feed. Then I opened the XML source of the feed and copied it to clipboard. Modified my GUI and added one more NSTextField which I used to paste XML feed data in and modified the Objective-C  Cocoa code like this:

	PSClient *client = [PSClient applicationClient];
	NSURL    *url    = [NSURL URLWithString:@"https://mail.google.com/mail/feed/atom/LABELNAME"];
	PSFeed   *feed   = [[[PSFeed alloc] initWithData:[txtInput.stringValue dataUsingEncoding:NSUTF8StringEncoding] URL:url] autorelease];
 
	feed.login = txtEmail.stringValue;
	[feed setPassword:txtPass.stringValue];
 
	NSLog(@"Err: %@", feed.lastError);
 
	// Retrieve the entries as an unsorted enumerator
	NSEnumerator *entries = [feed entryEnumeratorSortedBy: nil];
	PSEntry *entry;
 
	// Go through each entry and get what we need
	while (entry = [entries nextObject]) {
		NSLog(@"%@", entry.summary.plainTextString);
	}

And it finally worked fine. I parsed the feed manually and yeah, this isn’t exactly automated example but I did what I needed to do. And again, if anyone knows the solution to the authentication problem I’d love to hear it.