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 _____________________________________________________________________________________________________________________