Creating a public API method

The sample module code that Titanium creates as part of its module create process already provides us with a sample of a public method. We are going to create our own though which accepts a single string input value (the "long" URL) and then processes the short URL via the Bit.ly API before returning it to our Titanium app.

Getting ready

Before you can use the module, you'll need to sign up for a Bitly API Key, which you can do for free at: https://bitly.com/a/sign_up?rd=/a/your_api_key.

Additionally, we're going to need the open source SBJSON framework for Objective-C, which is capable of natively reading and writing JSON formatted data streams. You can download the SBJSON framework from https://github.com/stig/json-framework/.

Note

The complete source code for this recipe can be found in the /Chapter 10/Recipe 4 folder.

How to do it…

First, unzip the SBJSON framework, and drag all of the files from the Classes folder in Finder to the Classes folder in your module's XCode project.

Open up ComPacktpubBitlyModuleModule.h and ensure it looks like the following (ignoring the header comments at the top of the file):

#import "TiModule.h"
#import <Foundation/Foundation.h>

@interface ComPacktpubBitlyModuleModule : TiModule 
{
}


@end

Now open the ComPacktpubBitlyModuleModule.m file and ensure it looks like the following source code (ignoring the header comments at the top of the file). Remember to replace the login and key values in the QueryString section of the URL with those you were assigned by the Bit.ly API:

#import "ComPacktpubBitlyModuleModule.h"
#import "TiBase.h"
#import "TiHost.h"
#import "TiUtils.h"
#import "SBJson.h"
#import "SBJsonParser.h"

@implementation ComPacktpubBitlyModuleModule

#pragma mark Internal

// this is generated for your module, please do not change it
-(id)moduleGUID
{
   return @"a33e440e-ef62-4ec7-89cd-8939d264e46e";
}

// this is generated for your module, please do not change it
-(NSString*)moduleId
{
   return @"com.packtpub.BitlyModule";
}

#pragma mark Lifecycle

-(void)startup
{
   // this method is called when the module is first loaded
   // you *must* call the superclass
   [super startup];
   
   NSLog(@"[INFO] %@ loaded",self);
}

-(void)shutdown:(id)sender
{
   // this method is called when the module is being unloaded
   // typically this is during shutdown. make sure you don't 
      do too
   // much processing here or the app will be quit forceably

   // you *must* call the superclass
   [super shutdown:sender];
}

#pragma mark Cleanup 

-(void)dealloc
{
   // release any resources that have been retained by the module
   [super dealloc];
}

#pragma mark Internal Memory Management

-(void)didReceiveMemoryWarning:(NSNotification*)notification
{
   // optionally release any resources that can be dynamically
   // reloaded once memory is available - such as caches
   [super didReceiveMemoryWarning:notification];
}

#pragma mark Listener Notifications

-(void)_listenerAdded:(NSString *)type count:(int)count
{
   if (count == 1 && [type isEqualToString:@"my_event"])
   {
   // the first (of potentially many) listener is being added 
   // for event named 'my_event'
   }
}

-(void)_listenerRemoved:(NSString *)type count:(int)count
{
   if (count == 0 && [type isEqualToString:@"my_event"])
   {
   // the last listener called for event named 'my_event' has
   // been removed, we can optionally clean up any resources
   // since no body is listening at this point for that event
   }
}

#pragma Public APIs

-(id)example:(id)args
{
   // example method
   return @"hello world";
}

///creates the short url from bitly
- (id)getShortUrl:(id)value
{
    NSString *baseURLString = @"http://api.bit.ly/shorten?version=2.0.1&longUrl="; 
    NSString *longUrl = [TiUtils stringValue:value];

    longUrl = [longUrl stringByReplacingOccurrencesOfString:@"(" 
              withString:@""];
    longUrl = [longUrl stringByReplacingOccurrencesOfString:@")" 
              withString:@""];
    longUrl = [longUrl stringByReplacingOccurrencesOfString:@""" 
               withString:@""];
    longUrl = [longUrl 
              stringByTrimmingCharactersInSet:[NSCharacterSet 
              whitespaceAndNewlineCharacterSet]];
              baseURLString = [baseURLString 
              stringByAppendingString:longUrl];

    baseURLString = [baseURLString 
    stringByAppendingString:
    @"&login=REPLACE_YOUR_LOGIN&apiKey=REPLACE_YOUR_KEY"];
    NSURL* baseURL = [[NSURL alloc] 
       initWithString:baseURLString];

    NSMutableURLRequest *req = [[NSMutableURLRequest alloc] 
       initWithURL:baseURL];

   NSHTTPURLResponse* urlResponse = nil;  
   NSError *error = [[[NSError alloc] init] autorelease];  

   NSData *data = [NSURLConnection sendSynchronousRequest:req 
       returningResponse:&urlResponse error:&error];

   if ([urlResponse statusCode] >= 200 && [urlResponse 
       statusCode] < 300)
   {
        NSLog(@"Got a response from bit.ly");
          SBJsonParser* jsonParser = [SBJsonParser new];
          NSString* jsonString = [[NSString alloc] 
            initWithData:data encoding:NSUTF8StringEncoding];

         NSDictionary* dict = (NSDictionary*)[jsonParser 
              objectWithString:jsonString];

         [jsonString release];
         [jsonParser release];

         NSString *statusCode = [dict 
               objectForKey:@"statusCode"];

          if([statusCode isEqualToString:@"OK"])
          {
                 // retrieve shortURL from results
                 NSLog([dict description]);
                 NSString *shortURL = [[[dict 
                      objectForKey:@"results"]    
                      objectForKey:longUrl] 
                      objectForKey:@"shortUrl"];
                 return shortURL;
         }
        else
        {

            return @"Unable to shorten this URL, 
                     please check its format.";
        }        
   }

    return baseURLString;
}


@end

How it works…

The main function here is the one we created, called getShortUrl. All other methods and properties for the module have been auto-generated for us by the Titanium module creation scripts. This method, in short, executes a request against the Bit.ly API using our key and username, and when a response is received, it is parsed using the SBJSON parser. The resulting shortURL variable (of type NSString) is then pulled out of the shortURL element of the JSON result, and returned back to Titanium.

What we want to concentrate on here is the integration of the Titanium public method, and how the "value" argument is translated. Here we're using the (id) declaration, which allows us to easily typecast the incoming value to a parameter type that Objective-C understands. In this case, we are typecasting the "value" parameter to a type of NSString, as we know the incoming parameter is going to be a string value in the format of a web address. This conversion process is thanks to TiUtils , which we've imported at the top of our file using the #import "TiUtils.h" command.

Some of the most common conversion examples are:

CGFloat f = [TiUtils floatValue:arg];

NSInteger f = [TiUtils intValue:arg];

NSString *value = [TiUtils stringValue:arg];

NSString *value = [TiUtils stringValue:@"key" properties:dict def:@"default"];

TiColor *bgcolor = [TiUtils colorValue:arg];

We are also returning a string value which is either an error message (if the Bit.Ly conversion process failed) or, hopefully, the new short URL that Bit.Ly has kindly provided us. As we are returning a string, we don't need to perform a conversion before returning the parameter.

The following types can be returned without the need for typecasting:

  • NSString
  • NSDictionary
  • NSArray
  • NSNumber
  • NSDate
  • NSNull
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.139.224