14 Jun 2009

XML-RPC on the iPhone

Posted by kilbot | Filed under: News, Programming

This week I’ve been porting a simple J2ME mobile phone application to the iPhone. The J2ME application allows users to login and exchange data with a web application via XML-RPC, so naturally I was keen to use the same server-side scripts for the iPhone app. As far as I know, there is no no specific open source framework available for XML-RPC on the iPhone, but the folks at WordPress for iPhone have rolled their own which is available under the GNU General Public License, and with a little fishing around I was able to get it up and running in my own app. Basic instructions after the jump…

The first step is to download the WordPress for iPhone source code, either via SVN or directly through Trac (Link to the latest trunk: http://ios.trac.wordpress.org/browser/trunk).

When you extract that zip you will see a folder named Classes and inside that a folder named XMLRPC, drag the XMLRPC folder into your project. You will also need to grab NSString+XMLExtensions.h and NSString+XMLExtensions.m and drag them into your project.

That’s all the required files for the XML-RPC framework and now implementing is fairly straight forward. You need to put the following to your header file:

#import "XMLRPCResponse.h"
#import "XMLRPCRequest.h"
#import "XMLRPCConnection.h"

and to your .m file you need to add something like:

- (NSString *)loginToServer {
	NSArray *args = [NSArray arrayWithObjects:@"test",nil];   // the param(s)
	NSString *server = @"http://example.com/xmlrpc";         // the server
	NSString *method = @"loginUser";                        // the method
	XMLRPCRequest *request = [[XMLRPCRequest alloc] initWithHost:[NSURL URLWithString:server]];
	[request setMethod:method withObjects:args];
	id response = [self executeXMLRPCRequest:request];
	[request release];

	if( [response isKindOfClass:[NSError class]] ) {
		return nil;
	else {
		return [response valueForKey:@"key"];          // the response key
	return nil;

- (id)executeXMLRPCRequest:(XMLRPCRequest *)req {
	XMLRPCResponse *userInfoResponse = [XMLRPCConnection sendSynchronousXMLRPCRequest:req];
	return [userInfoResponse object];

You need to enter the appropriate values where I’ve commented, but this bare bones example should get you started. You can see more examples by sifting through BlogDataManager.m file in the WordPress for iPhone project.