NSDictionary objectAtKey returns (null)? July 31, 2009
Posted by Ameya in iPhone.Tags: iPhone, NSDictionary NSNull, NSDictionary null, NSNull, Tutorial
add a comment
A small work around for problem faced with NSDictionary null return problem.
In cases like
NSString *myImageURL = [user objectForKey:@"imageURL"];
where [user objectForKey:@"imageURL"] may return NSNull object.
This makes myImageURL a NSNull object hence cannot be compared using conventional comparisons. An NSNull is an invalid memory allocation or an error.:)
Two alternative solutions are
if ((NSNull *)[user objectForKey:@"imageURL"] == [NSNull null]) { }
and to convert to string if the above does not works.
NSString *myImageURL = [NSString stringWithFormat:@"%@",[user objectForKey:@"imageURL"]];
this can be compared by
if([imgURL isEqualToString:@""]){
}
iPhone Email Validation for Text Fieldone July 31, 2009
Posted by Ameya in iPhone, iPhone App Devlopment.Tags: iPhone, iPhone Email Validation, Tutorial
3 comments
Searched a lot for email validation for iPhone did not find any , hence was forced to create an validation method of my own.
Found an sample as below.
NSString *mystring = @"Hello World!"; NSString *regex = @".*l{2,}.*"; NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; if ([regextest evaluateWithObject:mystring] == YES) { NSLog(@"Match!"); } else { NSLog(@"No match!"); } The above code will not work as NSPredicate is not available for iPhone framework. Also found an sample that had the following code as below. RegexKitLite Objective-C ÕýÔò±í´ïʾ_ССµÄÌ«Ñô
NSString *email=@”asd@fgh.com”;
NSString *strEmailMatchstring=@”\\b([a-zA-Z0-9%_.+\\-]+)@([a-zA-Z0-9.\\-]+?\\.[a-zA-Z]{2,6})\\b”;
if(![email isMatchedByRegex:strEmailMatchstring]){
NSLog(@”Invalid email address found”);
objAlert = [[UIAlertView alloc] initWithTitle:@”Error!” message:
@”Enter a valid e-mail address” delegate:nil cancelButtonTitle:nil otherButtonTitles:@”Try Again”,nil];
[objAlert show];[objAlert release];
}
Found Regex download , which is available at http://downloads.sourceforge.net/regexkit/RegexKitLite-3.0.tar.bz2
* To include the RegexKitLite.h and RegexKitLite.m file in you project.
* In project setting search "other" at Other Linker Flags put the word "-licucore".
* Import header in the view controller where it will be used.
Modify the above method to as follows.
-(BOOL)emailValidate:(NSString *)email{
NSString *strEmailMatchstring=@"\\b([a-zA-Z0-9%_.+\\-]+)@([a-zA-Z0-9.\\-]+?\\.[a-zA-Z]{2,6})\\b";
if([email isMatchedByRegex:strEmailMatchstring])
return YES;
else
return NO;
}
Created an method of my own hope this would help people searching for such validation methods.
-(BOOL)emailValidate
NSString *)email{
//Based on the string below
//NSString *strEmailMatchstring=@”\\b([a-zA-Z0-9%_.+\\-]+)@([a-zA-Z0-9.\\-]+?\\.[a-zA-Z]{2,6})\\b”;
//Quick return if @ Or . not in the string
if([email rangeOfString:@"@"].location==NSNotFound || [email rangeOfString:@"."].location==NSNotFound)
return NO;
//Break email address into its components
NSString *accountName=[email substringToIndex: [email rangeOfString:@"@"].location];
email=[email substringFromIndex:[email rangeOfString:@"@"].location+1];
//’.’ not present in substring
if([email rangeOfString:@"."].location==NSNotFound)
return NO;
NSString *domainName=[email substringToIndex:[email rangeOfString:@"."].location];
NSString *subDomain=[email substringFromIndex:[email rangeOfString:@"."].location+1];
//username, domainname and subdomain name should not contain the following charters below
//filter for user name
NSString *unWantedInUName = @” ~!@#$^&*()={}[]|;’:\”<>,?/`”;
//filter for domain
NSString *unWantedInDomain = @” ~!@#$%^&*()={}[]|;’:\”<>,+?/`”;
//filter for subdomain
NSString *unWantedInSub = @” `~!@#$%^&*()={}[]:\”;’<>,?/1234567890″;
//subdomain should not be less that 2 and not greater 6
if(!(subDomain.length>=2 && subDomain.length<=6)) return NO;
if([accountName isEqualToString:@""] || [accountName rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:unWantedInUName]].location!=NSNotFound || [domainName isEqualToString:@""] || [domainName rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:unWantedInDomain]].location!=NSNotFound || [subDomain isEqualToString:@""] || [subDomain rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:unWantedInSub]].location!=NSNotFound)
return NO;
return YES;
}
NSASCIIStringEncoding breaks July 31, 2009
Posted by Ameya in iPhone.Tags: iPhone, NSASCIIStringEncoding, NSASCIIStringEncoding breaks, NSASCIIStringEncoding returns null, Tutorial
1 comment so far
It is possible that [subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], may return null, if subject contains ASCII charter out side 0 to 127.
NSString *mailString = [NSString stringWithFormat:@"mailto
to=%@&subject=%@&body=%@",
[to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
[body stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailString]];
To stop this we can use an simple filter like.
-(NSString *)replaceLatin
NSString *)string{
return [[[[[[[[[[[[string stringByReplacingOccurrencesOfString:@"–" withString:@""] stringByReplacingOccurrencesOfString:@”—” withString:@”"] stringByReplacingOccurrencesOfString:@”¡” withString:@”"] stringByReplacingOccurrencesOfString:@”¿” withString:@”"] stringByReplacingOccurrencesOfString:@””” withString:@”"] stringByReplacingOccurrencesOfString:@”“” withString:@”"] stringByReplacingOccurrencesOfString:@”\”" withString:@”"] stringByReplacingOccurrencesOfString:@”‘” withString:@”"] stringByReplacingOccurrencesOfString:@”’” withString:@”"] stringByReplacingOccurrencesOfString:@”‘” withString:@”"] stringByReplacingOccurrencesOfString:@”«” withString:@”"] stringByReplacingOccurrencesOfString:@”»” withString:@”"];
}
Apple Push Notification Service Tutorial July 31, 2009
Posted by Ameya in iPhone, iPhone App Devlopment.Tags: iPhone, Tutorial
61 comments
Apple Push Notification Service (APNS) an service user by apple to notify application. The notification can be of various Text Alert with or without sound, Baggage number update on icon etc.
Below are the steps to construct an simple application that receives notification form APNS.
The steps are for development testing on sandbox APNS service from Apple
Getting Ready with Certificate and key.
- Generate a certificate signing request from your Mac’s keychain and save to disk.(Steps same as creating certificate for development but don’t submit not).
Pleas store this certificate in a safe location as it might be re-required to invoke APNS. - Login into your development account and visit iPhone Developer Program Portal.
- Click App IDs on left. Create an new id without wild charter (com.mydomain.applicationName). This name will be used while setting up your application to be signed with development certificate. If you use wild character like ‘*’ the iPhone Developer Program Portal will not allow the App ID to be used for notification.
- After submitting the new App ID you will be guided to the list page. Click configure to edit setting. Check ‘Enable for Apple Push Notification service’ to enable APNS , and click Configure next to ‘Development Push SSL Certificate’.
- Upload your request certificate generated in step 1 and download the certificate (aps_developer_identity.cer) from the Program Portal
. Double click on this certificate to save it your key chain. Export this key by clicking on this newly installed certificate. The exported key is saved as Certificate.p12 file on your system. Please store it other files uploaded or downloaded from portal program. This .p12 file is used in later steps for signing your Provider server. - Click on Provisioning in left bar and create a new provisioning profile. Use the new created App Id and select the device you want to use for development. Download the new provisioning profile save with other files. Close XCode if open and drag drop new provisioning profile on your XCode in your Doc bar.Your ready with certificate and key.
Getting ready with the application
- Create an simple view based application.
- Paste these line of code in your application.
- (void)applicationDidFinishLaunching:(UIApplication *)app {
// other setup tasks here….
[window addSubview:viewController.view];
[self alertNotice:@"" withMSG:@"Initiating Remote Noticationss Are Active" cancleButtonTitle:@"Ok" otherButtonTitle:@""];
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound)];
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
//NSLog(@”devToken=%@”,deviceToken);
[self alertNotice:@"" withMSG:[NSString stringWithFormat:@"devToken=%@",deviceToken] cancleButtonTitle:@”Ok” otherButtonTitle:@”"];
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSLog(@”Error in registration. Error: %@”, err);
[self alertNotice:@"" withMSG:[NSString stringWithFormat:@"Error in registration. Error: %@", err] cancleButtonTitle:@”Ok” otherButtonTitle:@”"];
}
-(void)alertNotice:(NSString *)title withMSG:(NSString *)msg cancleButtonTitle:(NSString *)cancleTitle otherButtonTitle:(NSString *)otherTitle{
UIAlertView *alert;
if([otherTitle isEqualToString:@""])
alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:cancleTitle otherButtonTitles:nil,nil];
else
alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:cancleTitle otherButtonTitles:otherTitle,nil];
[alert show];
[alert release];
}
- Please be careful with the error reporting part in the code as error tell a lot about the development state.
- Right click on the application in target in the left and click Get Info to configure the application. Click on property tab and paste your App ID in the identifier text-field.
- Click build tab, select debug and select your new provisioning profile.
- Click Device 3.0 and Build Go to distribute binary to your connected device.
- Starting the application it should first alert and message that it registering for notification. Followed by and alert the application is registering for notification allow or deny. Followed by an alert that displays the device token ID. Note this token as this will be used by your server code to communicate with your device. If the second message is error then either something has gone wrong with the certificate and your application cannot register your certificate start over again.
Getting ready with Notification service provider.
Download an stand alone MAC application (PushMeBaby http://stefan.hafeneger.name/download/PushMeBabySource.zip) to test. There are two modification in the application to get started.
Place an copy of the aps_developer_identity.p12 file in the application folder. Import the file in the application by right clicking and Add > Existing File.
Set the following in the application’s delegate file as shown below
self.deviceToken = @”XXXXX XXXXX XXXXX XXXXXX XXXXXX”;
//First your device id token.
self.payload = @”{\”aps\” : { \”alert\” : \”You got your emails.\”,\”badge\” : 9,\”sound\” : \”bingbong.aiff\”},\”acme1\” : \”bar\”,\”acme2\” : 42}”;
//The pay load
self.certificate = [[NSBundle mainBundle] pathForResource:@”aps_developer_identity” ofType:@”cer”]; //The certificate file.
- Don’t depend on the application’s text-field as it doesn’t work.
- Start the application and you will get a message the application is trying to access your key , click ‘Allow’. Click Push in the application window. Wait for a 20 seconds and you should immediately get an notification on your iPhone / iTouch.
Getting ready with test code for actual provider sever (PHP).
- For server on linux environment you will require different kind of certificate. Following are the steps to create it. Use MAC console to fire the following commands.
openssl pkcs12 -clcerts -nokeys -out cert.pem -in Certificate.p12
provide new password if asked.
openssl pkcs12 -nocerts -out key.pem -in Certificate.p12
provide new password if asked.
cat cert.pem key.unencrypted.pem > ck.pem
Create an PHP file provide.php
$message);
if ($badge)
$body['aps']['badge'] = $badge;
if ($sound)
$body['aps']['sound'] = $sound;
/* End of Configurable Items */
$ctx = stream_context_create();
stream_context_set_option($ctx, ‘ssl’, ‘local_cert’, ‘ck.pem’);
// assume the private key passphase was removed.
// stream_context_set_option($ctx, ‘ssl’, ‘passphrase’, $pass);
$fp = stream_socket_client(‘ssl://gateway.sandbox.push.apple.com:2195′, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
if (!$fp) {
print “Failed to connect $err $errstrn”;
return;
}
else {
print “Connection OKn”;
}
$payload = json_encode($body);
$msg = chr(0) . pack(“n”,32) . pack(‘H*’, str_replace(‘ ‘, ”, $deviceToken)) . pack(“n”,strlen($payload)) . $payload;
print “sending message :” . $payload . “n”;
fwrite($fp, $msg);
fclose($fp);
?>
Note : Your PHP server must have json_encode support.
Run your file on linux console as ‘php provide.php’
For more information refer http://www.macoscoders.com/2009/05/17/iphone-apple-push-notification-service-apns/
_____________________________________________________________________________________________________________________
There is an open source PHP/MySQL back-end for APNS. So if you want your own integration of push notifications on your own server, here you goGoogle Code: http://code.google.com/p/easyapns/
Google Group: http://groups.google.com/group/easyapns contributed by [mrmidi] manifestinteractive@gmail.com _____________________________________________________________________________________________________________________
2010 in review January 3, 2011
Posted by Ameya in Uncategorized.add a comment
The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:

The Blog-Health-o-Meter™ reads This blog is on fire!.
Crunchy numbers
About 3 million people visit the Taj Mahal every year. This blog was viewed about 28,000 times in 2010. If it were the Taj Mahal, it would take about 3 days for that many people to see it.
In 2010, there were 4 new posts, growing the total archive of this blog to 10 posts.
The busiest day of the year was September 28th with 159 views. The most popular post that day was Apple Push Notification Service Tutorial.
Where did they come from?
The top referring sites in 2010 were iphonedevsdk.com, google.co.in, davidbits.blogspot.com, google.com, and cocoachina.com.
Some visitors came searching, mostly for iphone push notification tutorial, uiview animation tutorial, iphone animation tutorial, push notification tutorial, and iphone view animation.
Attractions in 2010
These are the posts and pages that got the most views in 2010.
Apple Push Notification Service Tutorial July 2009
55 comments
View Animation Tutorial August 2009
3 comments
iPhone Email Validation for Text Fieldone July 2009
2 comments
No launchable executable present at path August 2009
LinkedIn API and Twitter API access using GOOGLE Data API June 2010
3 comments
Drop Down Custom View For iPhone applications. September 26, 2010
Posted by Ameya in iPhone, iPhone App Devlopment.3 comments
Wanted to have a drop-down view like we have in html element, allows user to select one option form list of option.
Have created sample application that demonstrates the use of this custom view.
Sample project available to download at http://code.google.com/p/dropdowndemo/downloads/list.
Adding instruction how to use view in you application.
- Import QuartzCore.framework in your application.
- Import DropDownView.h file in the view controller.
- Have an class variable dataArray to store data to be put into the table and make a class variable of DropDownView. Making DropDownView variable allows you to control the DropDownView.
- Use the DropDownViewDelgate and declare the delegate method in your application.
- Initialize the DropdownView variable and add the view in your current view, andy your ready to go.
Below a demo sample classes.
FirstController.h
--------------------
#import <UIKit/UIKit.h>
#import "DropDownView.h"
@interface FirstController : UIViewController<DropDownViewDelegate> {
UIButton *button;
NSArray *arrayData;
DropDownView *dropDownView;
}
@property (nonatomic,retain) IBOutlet UIButton *button;
-(IBAction)actionButtonClick;
@end
--------------
FirstController.m
-----------
#import "FirstController.h"
@implementation FirstController
@synthesize button;
- (void)viewDidLoad {
[super viewDidLoad];
arrayData = [[NSArray alloc] initWithArray:[NSArray arrayWithObjects:@"Test1",@"Test2",nil]];
dropDownView = [[DropDownView alloc] initWithArrayData:arrayData cellHeight:30 heightTableView:200 paddingTop:-8 paddingLeft:-5 paddingRight:-10 refView:button animation:BLENDIN openAnimationDuration:2 closeAnimationDuration:2];
dropDownView.delegate = self;
[self.view addSubview:dropDownView.view];
[button setTitle:[arrayData objectAtIndex:0] forState:UIControlStateNormal];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[button release];
[super dealloc];
}
#pragma mark -
#pragma mark DropDownViewDelegate
-(void)dropDownCellSelected:(NSInteger)returnIndex{
[button setTitle:[arrayData objectAtIndex:returnIndex] forState:UIControlStateNormal];
}
#pragma mark -
#pragma mark Class methods
-(IBAction)actionButtonClick{
[dropDownView openAnimation];
}
@end
------------
DropDownView.h
------------------- #import <UIKit/UIKit.h> typedef enum {
BLENDIN,
GROW,
BOTH
} AnimationType; @protocol DropDownViewDelegate @required -(void)dropDownCellSelected:(NSInteger)returnIndex; @end @interface DropDownView : UIViewController<UITableViewDelegate,UITableViewDataSource> { UITableView *uiTableView; NSArray *arrayData; CGFloat heightOfCell; CGFloat paddingLeft; CGFloat paddingRight; CGFloat paddingTop; CGFloat heightTableView; UIView *refView; id<DropDownViewDelegate> delegate; NSInteger animationType; CGFloat open; CGFloat close; } @property (nonatomic,assign) id<DropDownViewDelegate> delegate; @property (nonatomic,retain)UITableView *uiTableView; @property (nonatomic,retain) NSArray *arrayData; @property (nonatomic) CGFloat heightOfCell; @property (nonatomic) CGFloat paddingLeft; @property (nonatomic) CGFloat paddingRight; @property (nonatomic) CGFloat paddingTop; @property (nonatomic) CGFloat heightTableView; @property (nonatomic,retain)UIView *refView; @property (nonatomic) CGFloat open; @property (nonatomic) CGFloat close; - (id)initWithArrayData:(NSArray*)data cellHeight:(CGFloat)cHeight heightTableView:(CGFloat)tHeightTableView paddingTop:(CGFloat)tPaddingTop paddingLeft:(CGFloat)tPaddingLeft paddingRight:(CGFloat)tPaddingRight refView:(UIView*)rView animation:(AnimationType)tAnimation openAnimationDuration:(CGFloat)openDuration closeAnimationDuration:(CGFloat)closeDuration; -(void)closeAnimation; -(void)openAnimation; @end
----------
DropDownView.m
------------
#import "DropDownView.h"
#import <QuartzCore/QuartzCore.h>
@implementation DropDownView
@synthesize uiTableView;
@synthesize arrayData,heightOfCell,refView;
@synthesize paddingLeft,paddingRight,paddingTop;
@synthesize open,close;
@synthesize heightTableView;
@synthesize delegate;
- (id)initWithArrayData:(NSArray*)data cellHeight:(CGFloat)cHeight heightTableView:(CGFloat)tHeightTableView paddingTop:(CGFloat)tPaddingTop paddingLeft:(CGFloat)tPaddingLeft paddingRight:(CGFloat)tPaddingRight refView:(UIView*)rView animation:(AnimationType)tAnimation openAnimationDuration:(CGFloat)openDuration closeAnimationDuration:(CGFloat)closeDuration{
if ((self = [super init])) {
self.arrayData = data;
self.heightOfCell = cHeight;
self.refView = rView;
self.paddingTop = tPaddingTop;
self.paddingLeft = tPaddingLeft;
self.paddingRight = tPaddingRight;
self.heightTableView = tHeightTableView;
self.open = openDuration;
self.close = closeDuration;
CGRect refFrame = refView.frame;
self.view.frame = CGRectMake(refFrame.origin.x-paddingLeft,refFrame.origin.y+refFrame.size.height+paddingTop,refFrame.size.width+paddingRight, heightTableView);
self.view.layer.shadowColor = [[UIColor blackColor] CGColor];
self.view.layer.shadowOffset = CGSizeMake(5.0f, 5.0f);
self.view.layer.shadowOpacity =1.0f;
self.view.layer.shadowRadius = 5.0f;
animationType = tAnimation;
}
return self;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
CGRect refFrame = refView.frame;
uiTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0,refFrame.size.width+paddingRight, (animationType == BOTH || animationType == BLENDIN)?heightTableView:1) style:UITableViewStylePlain];
uiTableView.dataSource = self;
uiTableView.delegate = self;
[self.view addSubview:uiTableView];
self.view.hidden = YES;
if(animationType == BOTH || animationType == BLENDIN)
[self.view setAlpha:1];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[super dealloc];
[uiTableView release];
[arrayData,refView release];
}
#pragma mark -
#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return heightOfCell;
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return [arrayData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [arrayData objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[delegate dropDownCellSelected:indexPath.row];
[self closeAnimation];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
return 0;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return @"";
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
return @"";
}
#pragma mark -
#pragma mark DropDownViewDelegate
-(void)dropDownCellSelected:(NSInteger)returnIndex{
}
#pragma mark -
#pragma mark Class Methods
-(void)openAnimation{
self.view.hidden = NO;
NSValue *contextPoint = [[NSValue valueWithCGPoint:self.view.center] retain];
[UIView beginAnimations:nil context:contextPoint];
[UIView setAnimationDuration:open];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
[UIView setAnimationRepeatCount:1];
[UIView setAnimationDelay:0];
if(animationType == BOTH || animationType == GROW)
self.uiTableView.frame = CGRectMake(uiTableView.frame.origin.x,uiTableView.frame.origin.y,uiTableView.frame.size.width, heightTableView);
if(animationType == BOTH || animationType == BLENDIN)
self.view.alpha = 1;
[UIView commitAnimations];
}
-(void)closeAnimation{
NSValue *contextPoint = [[NSValue valueWithCGPoint:self.view.center] retain];
[UIView beginAnimations:nil context:contextPoint];
[UIView setAnimationDuration:close];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
[UIView setAnimationRepeatCount:1];
[UIView setAnimationDelay:0];
if(animationType == BOTH || animationType == GROW)
self.uiTableView.frame = CGRectMake(uiTableView.frame.origin.x,uiTableView.frame.origin.y,uiTableView.frame.size.width, 1);
if(animationType == BOTH || animationType == BLENDIN)
self.view.alpha = 0;
[UIView commitAnimations];
[self performSelector:@selector(hideView) withObject:nil afterDelay:close];
}
-(void)hideView{
self.view.hidden = YES;
}
@end
LinkedIn API and Twitter API access using GOOGLE Data API June 9, 2010
Posted by Ameya in iPhone, iPhone App Devlopment.4 comments
LinkedIn API access using Google Data Api
Was facing problem linkedin API access using a suitable oauth client framework for iPhone.
The problem was there was no proper solution for this.
I had already come accross Google data API and their touch sample code available at http://code.google.com/p/gdata-objectivec-client/. which I was tring to access gmail for mails, but seems they have not opened that yet, although they provide access to Contact api.
Struggling to find an api access to linked in from iPhone stumbled upon this thread http://developer.linkedin.com/thread/1447 which redirected me to this http://developer.linkedin.com/thread/1169. Here you will find a lot of comments and sample application created by “Scott” and if u mail him you will get the source.
But still I was not satisfied as I wanted to use MPOAuthMobile for iPhone for a unified access to twitter and linkedin.
So here is the simple and elegant solution using Google Data API , (you can trust google so I prefer it as a solution).
Simply download the the sample from http://code.google.com/p/gdata-objectivec-client/
Replace twitter
keys as below
NSString *myConsumerKey = @”XXXXXXXXX”; //NEED TO ENTER YOUR CONSUMER
KEY FROM LINKEDIN API
NSString *myConsumerSecret = @”XXXXXX”; //NEED TO ENTER YOUR CONSUMER
SECRET FROM LINKEDIN API
I accept that you have a consumer secrete and key. Else get it by registering your application at https://www.linkedin.com/secure/developer
and replace the URL set as below
NSURL *requestURL = [NSURL URLWithString:@"
https://api.linkedin.com/uas/oauth/requestToken"];
NSURL *authorizeURL = [NSURL URLWithString:@"
https://api.linkedin.com/uas/oauth/authorize"];
NSURL *accessURL = [NSURL URLWithString:@"
https://api.linkedin.com/uas/oauth/accessToken"];
NSString *scope = nil;
do not forget to replace this with your reverse domain name as
static NSString *const kAppServiceName = @”com.YOURDOMAIN.OAuthSampleTouch”;
static NSString *const kShouldSaveInKeychainKey = @”shouldSaveInKeychain”;
Run your application, click twiter tab and singin.
You should get a web view where you can login and the application pops back to return the oauth token.
This is where I got the solution
http://groups.google.com/group/gdata-objectivec-client/browse_thread/thread/d876c078b677334/5981e36d77c2151f?lnk=gst&q=Can+we+use+OAuth+Sample+provided+in+google+data+api+to+work+with+LinkedIn+Api#5981e36d77c2151f
Twitter API access using Google Data API
The application provided google should simply work simply you have take care of the following points.
Create your application at https://twitter.com/apps
- Application Type: Browser not client ( if is a client application
then will prompt for a pin which is used in the application to
authenticate.). - Website: provide some web site.
- Use Twitter for login: check mark Yes, use Twitter for login.
- Callback URL: http://www.google.com/OAuthCallback
Twitter with JSON and fetching id from NSDictionary April 17, 2010
Posted by Ameya in 1.Tags: garbeld integer, JSON, NSDictionary, Twitter
2 comments
Was working with twitter API to get tweets in to iPhone. Found another silly issue , which solved with great effort.
Was using some kind of JSON parser ,(will put the name later) , to fetch tweets. every thing was running fine until I wanted to store the latest tweet’s status_id. Here I ran into serious trouble. I was using integer in the database and keeping the tweet_status _id as my tuple (table row) identity. The problem I faced here was all other things converted well like the user id , tweet text etc. when tried to convert status_id would find some garbled entry , really strange. After long unsuccessful efforts in converting twitter status id in to integer , I finally noticed that the size of the number was very big. Bingo the solution was not far just need to convert NSString to double value. So I thought of some fixed approach to deal with twitter data.
- Better not store the converted form of twitter data in the database, for data like status ids, I store it as char or text. Convert it to its true form only when required to compare , like need to store the max status tweet id by comparing with rest tweets id.
- Never keep twitter status as identity in your table. Remember in iPhone your using SQLite db.
- The only two fields can cause serious problem in future in the application are tweet’s status id and tweet’s status’s user id. Better keep them as text and handle them as double. the use id fit as a integer now , but soon will be out of integer scoop.
This post I have put up to show some light to developers goggling for the problem I faced. Please comment to impove this post and, I will include the points it the main post itself.
SQLite Abort due to constraint violation April 17, 2010
Posted by Ameya in iPhone App Devlopment.Tags: 19, abort, Abort due to constraint violation, SQLite, violation
1 comment so far
When working with SQLite connections with iPhone , encounter a strange problem.
- Records where not getting inserted into database .
- Existing records could not be updated.
- The log and NSAssertion showed now error.
Tried to debug and found that the SQLite message after committing to db was 19 (SQLITE_CONSTRAINT) , this did not convey much information. Drilled down the SQLite static for the message and found “Abort due to constraint violation” for meaage 19. Googled but could not find much of help out there, and my project was stranded. While checking every thing from scratch found that thee where condition enforced on the column of table NOT NULL, like id was PRIMAY KEY AUTO INCREMENT NOT NULL. This was the cause of the issue , as I wanted the SQLite to generate id for me but also had said you require an id field for an insertion to complete. The same problem was with some other column.
So I decided to keep some guideline for dealing with SQLite and iPhone connections.
- Never create primary key column of table with both the restrictions ON (TUE) , that is AUTO INCREMENT NOT NULL. This rule can ignored, if you want to manage your own primary key creation.
- Never create column of table with restrictions NOT NULL, unless you are absolutely sure you will always have a value for the column. This rule can be ignored if you are managing NULL value entries in UI input fields from SQLite connection. No one uses this approach, of checking NULL from SQL, as every one wants to check input from the view in the controller itself. So this rule must not be broken.
- When dealing with sqlite3_step() don’t depend on SQLITE_ERROR (1) ( SQL error or missing database ) to catch error with your SQL statements. Better look for SQLITE_DONE (101) ( has finished executing successfully), rest everything is an error, even constrain violation.
My post may look silly, for an expert but even an expert makes a silly mistake.
No launchable executable present at path August 18, 2009
Posted by Ameya in iPhone, iPhone App Devlopment.2 comments
I was having problem ” No launchable executable present at path ” when migrating from 2.2.1 sdk to 3.0 sdk. Althoug the application had 0 error and 0 warning the state continued. I got this problem solved by following these 2 steps.
- Close all instance and main xcode application.
- Go to application folder of concern and simply delete the build folder and click the xcode executable in your application folder to start.
This should solve your problem.
View Animation Tutorial August 17, 2009
Posted by Ameya in iPhone, iPhone App Devlopment.4 comments
Lets start by taking a simple view based application.
Open the view controller class file of the application and you will find an commented method ” -(void)viewDidLoad” copy past the following line of code in the scope of the method.
[super viewDidLoad];
/* Simple Viewable red rectrangle */
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100,100,100,50)];
view.backgroundColor = [UIColor redColor];
[self.view addSubview:view];
/* Create simple animation */
//Create context for animation
NSValue *contextPoint = [[NSValue valueWithCGPoint:view.center] retain];
[UIView beginAnimations:nil context:contextPoint];
//Animation duration in float
[UIView setAnimationDuration:5];
//Animation process curve
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//Animation repeate
[UIView setAnimationRepeatCount:1];
//Animation start after delay
[UIView setAnimationDelay:1];
//Apply transformations in combination to the view
view.transform = CGAffineTransformConcat(
CGAffineTransformConcat(
CGAffineTransformConcat(
CGAffineTransformMakeTranslation(-12,0),CGAffineTransformMakeScale(3,3)),
CGAffineTransformMakeRotation(3.14)),
CGAffineTransformMake(1,2,3,4,5,6));
[UIView commitAnimations];
- The above comments for the pice of code are self explanatory.
- Lines 5 to 7 help to create simple res rectangle and adds as a sub-view of the current view.
- Now for animation we have to create an canvas which is called our context. The context is created with the line 11 and 12.
- Now we have to tell what the animation should be like.
- Line 5 states that the entire animation will be completed in 5 seconds. The input is fraction hence takes in 5.5 etc also.
- Line 18 states the animation curve, that is what speed the animation should proceed. The variant of the values are.
UIViewAnimationCurveEaseInOut
An ease-in ease-out curve causes the animation begins slowly, accelerate through the middle of its
duration, and then slow again before completing.
Available in iPhone OS 2.0 and later.
Declared in UIView.h.
UIViewAnimationCurveEaseIn
An ease-in curve causes the animation to begin slowly, and then speed up as it progresses.
Available in iPhone OS 2.0 and later.
Declared in UIView.h.
UIViewAnimationCurveEaseOut
An ease-out curve causes the animation to begin quickly, and then slow as it completes.
Available in iPhone OS 2.0 and later.
Declared in UIView.h.
UIViewAnimationCurveLinear
A linear animation curve causes an animation to occur evenly over its duration.
Available in iPhone OS 2.0 and later.
Declared in UIView.h.
- Line 21 states how many repetation of the animation are required. Takes fraction input but not 0 to denote infinite loops, but we have to specify the number of loop. try changing the value to 1.5 in your application. The animation will run once full then a half.
- Line 24 states the delay after which the animation should start.
- Line 27 is the core of the animation process. The various transformations that should be animated. This step consists of 4 transformations all concatenation into one transformation.
- There are basic 4 transforms
- CGAffineTransformMakeTranslation(-12,0) This statement states that your context will move to left by 12 px and 0 up or down.
- CGAffineTransformMakeScale(3,3) Will multiply the width and height by 3 and 3 respectively.
- CGAffineTransformMakeRotation(3.14) Will rotate the context by (pi) 3.14 . You can rotate from 0(0) to 180 ((pi) 3.14) degress repectively (clock wize for positive and anti clock wise for negative.).
- CGAffineTransformMake(1,2,3,4,5,6) This statement directly works on the animation matrix. For more information on this. ref wiki and iPhone docs.
The last statement actually starts the animation.
- This is a small picture to animate small rectangle the complete view can be animated transformational similarly.





