Monday, December 28, 2009

Cookie Management in iPhone

The following code may help people who are looking for some sort of cookie management for their iPhone web application. This post will definitely get you started.

NSURLCredential *userCredentials = [NSURLCredential credentialWithUser:email.text

NSURLProtectionSpace *space = [[NSURLProtectionSpace alloc] initWithHost:@"localhost"
authenticationMethod: NSURLAuthenticationMethodDefault];

[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:userCredentials

After writing the above code, your application will be able to store cookies for the site http://localhost:3000/. You may also change it as per your need and requirement, such as:

* May use three different types of persistence storage for cookies: NSURLCredentialPersistenceNone,

* May use different authentications. AuthenticationMethod should be set to one of the values in NSString *NSURLProtectionSpaceHTTPProxy;
NSString *NSURLProtectionSpaceHTTPSProxy;
NSString *NSURLProtectionSpaceFTPProxy;
NSString *NSURLProtectionSpaceSOCKSProxy;

or nil to use the default, NSURLAuthenticationMethodDefault.

For more information, refer to Apple's documentation.

Tuesday, December 15, 2009

Sound Playback in iPhone

Today I am going to post two ways to play sounds in iPhone.

1st Approach: Using Audio Toolbox
NSString *sound = [NSString stringWithFormat:@"sound"];
NSString *path = [[NSBundle mainBundle] pathForResource:sound ofType:@"wav"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);

Of course, for this to work you need to add the AudioToolbox foundation to your project. Also it doesn't like the compressed audio of mp3's, etc. It is more suited for wav's.

2nd Approach: Using AVAudioPlayer class
The AVAudioPlayer class makes it very easy to play mp3s as well.

NSString *newAudioFile = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"mp3"];

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:newAudioFile] error:NULL];

[audioPlayer setDelegate:self];
[audioPlayer prepareToPlay];
BOOL plays = [audioPlayer play];


For this to work, you need to add the AVFoundation to your project:
Project -> Add ->

Make sure to NOT copy it into your project when you are given the dialog box.

AVAudioPlayer provides a really straightforward interface, but it might not be appropriate for playing really short sounds that are synchronized with your app. AudioServices is really intended to play short sounds, and it works very well for that.

Adding the following line to your code, before you start the player, should cause the audioPlayer to loop indefinitely, until you issue a stop message:
[audioPlayer setNumberOfLoops:-1];

after the setDelegate function call.

Note that, with MP3, you may run into issues if you need to play multiple sounds at the same time:

Coding How-Tos: Audio and Video
The following limitations pertain for simultaneous sounds in iPhone OS, depending on the audio data format:

* AAC, MP3, and ALAC (Apple Lossless) audio: no simultaneous playback; one sound at a time.

Monday, November 16, 2009

Password Protect a Folder on the Mac

I was looking for a way to password protect a folder on the Mac. After a lot of research I found out a way of creating a disk image to protect our stuff in really a simple manner. I would like to mention its procedure in steps:

*First open up the “Disk Utility” application.
*Go to File -> New -> Disk Image from Folder
*Chose a folder to protect
*The next, most important part, is the encryption. You can pick either 128, or 256 bit encryption, it really doesn’t matter. I would recommend 128 bit due to speed although if you want to be extra safe pick the second option. Make sure the Image Format at the bottom is set to read/write, so you can write files into the disk image.

Once as you click ok, the engine will start working and it will create your disk image.

Enter your desired new password twice (Do not forget it.)

Once as you click ok, the image will mount and you have a standard image. You can then add in the files you want.This process creates an ordinary Macintosh disk image (.dmg) file. The disk image contains the entire contents of the folder, but cannot be opened unless the correct password is supplied. To open it, just double-click the .dmg file in Finder. A password dialog box will appear. Once you supply your correct password, Finder will automatically unencrypt your data and mount the image as a disk.

To be extra secure you may have to delete the Keychain password as it stores it by default. To do this open up Keychain Access, find your file in the list and delete it. You will then have to enter the image password if you want to access your files.

If you ever need to increase the size of you image because you have filled it up it is pretty simple. Make sure you have opened and closed Disk Utility. Click on the disk image you have created and then on Resize Image in the tool bar. Once as the box pops open click on the blue down arrow. Click on Resize Image, this will then enable you to increase the size of the image all the way up to the maximum free space on your disk. Once as you have done this you are done.

Hopefully, if you have followed the instructions OK, you will be able to password protect your files, and as a result of folder. Until Apple release a way of doing this in Finder, or the Get Info pane.

Thursday, November 5, 2009

iPhone: Shake to Update

Many applications perform some basic functions(like updating the UI, playing a sound etc.) when user shakes the iphone. Following snippet shows how to add this functionality in your app:

//In the .h file add the like this:
@interface TableViewController : UIViewController
//Add these two variables in the .h
BOOL shakeDetected;
UIAcceleration* lastAcceleration;
//Create a property
@property (retain) UIAcceleration* lastAcceleration;

//In the .m synthesize your property
@synthesize lastAcceleration;

//In the .m file, in your viewdidload add this line
[UIAccelerometer sharedAccelerometer].delegate = self;

//Add this method to the .m file
//Shake Detection Part 1
static BOOL IsDeviceShaking(UIAcceleration* last, UIAcceleration* current, double threshold) {
double deltaX = fabs(last.x - current.x);
double deltaY = fabs(last.y - current.y);
double deltaZ = fabs(last.z - current.z);
return (deltaX > threshold && deltaY > threshold) ||
(deltaX > threshold && deltaZ > threshold) ||
(deltaY > threshold && deltaZ > threshold);

//And add this method to the .m file also
//Shake Detection Part 2
- (void) accelerometer: (UIAccelerometer *)accelerometer didAccelerate: (UIAcceleration *)acceleration {
if (self.lastAcceleration) {
if (!shakeDetected && IsDeviceShaking(self.lastAcceleration, acceleration, 0.7)) {
shakeDetected = YES;
//This is where you put what you want to happen when it shakes
//The line below reloads the table
[tableView reload];
else if (shakeDetected && !IsDeviceShaking(self.lastAcceleration, acceleration, 0.2)) {
shakeDetected = NO;
self.lastAcceleration = acceleration;

Wednesday, October 7, 2009

Backup of mysql database

I usually need to backup my (mysql) database for transferring it from one pc to another or to transfer it to my partner working on the same project or to take a back up of the production database of my website. We could do it simply using a single command from the command prompt:

mysqldump [options] db_name [tables]

You could use this command as:
mysqldump -u root project_production > backup.sql
mysqldump project_production > backup.sql
(depending on the permissions)

This will generate a file backup.sql in your current directory which could be used to regenerate the database any time in future on the same or different pc.

Importing the data from the backup file is much more simpler. Just type on the command prompt:
mysql -u root project_development < backup.sql

This will copy all the data from the backup file to another database named project_development.

For more information, visit this site.

Thursday, September 10, 2009

Shuffle/Randomize Arrays (iPhone)

iPhone programming is a bit different task, you have to write a lot of code just for a small task. Have you ever need to randomize an array of items? It's a task that, for some reason, needs to be used a lot (at least for me). So, I am showing you a simple way to handle this task.


#import "UIKit/UIKit.h"

@interface NSArray(Shuffle)
-(NSArray *)shuffledArray;


#import "ShuffleArray.h"

@implementation NSArray(Shuffle)
-(NSArray *)shuffledArray

NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count]];

NSMutableArray *copy = [self mutableCopy];
while ([copy count] > 0)
int index = arc4random() % [copy count];
id objectToMove = [copy objectAtIndex:index];
[array addObject:objectToMove];
[copy removeObjectAtIndex:index];

[copy release];
return array;

Tuesday, July 28, 2009

ATTENSION!! All computer users..

For everyone who works daily on a computer. The mistakes daily mouse and keyboard usage will result in Carpal Tunnel Syndrome! Use the mouse and keyboard correctly. View below for the surgery of a patient suffering from Carpal Tunnel Syndrome followed by the 
RIGHT TECHNIQUES for usage....

Hand exercises for Carpal Tunnel Syndrome

Thursday, June 18, 2009

How to install ruby and related gems on Mac OS X (Leopard)


Type these commands into Terminal:

curl -O
tar xzvf ruby-1.8.7-p72.tar.gz
cd ruby-1.8.7-p72
./configure --enable-shared --enable-pthread CFLAGS=-D_XOPEN_SOURCE=1
sudo make install
cd ..

To verify that Ruby is installed and in your path, just type:

which ruby

You should see:



After installing ruby, move on to ruby gems the same way:

curl -O
tar xzvf rubygems-1.3.1.tgz
cd rubygems-1.3.1
sudo /usr/local/bin/ruby setup.rb
cd ..

Ruby on Rails and other gems

Now you are ready to install important gems:

sudo gem install rails

sudo gem install mysql

or do it in a single step like:

sudo gem install RedCloth termios rspec sake capistrano mongrel

Congratulations! You are done with the basic setup of ruby and rails.

Tuesday, April 28, 2009

Applications on AppStore

Some of the applications developed by me are available on the AppStore for download. I would like to give their details:

1) GK Quiz (iTunes_url =>
Amazing quiz to test and enhance your knowledge. Give correct answers to asked questions and score more and more points. Referred as one of the best GK application for kids.

Three different quiz modes:
- country/capital
- country/currency
- country/nickname

2) Slots & Archer (iTunes_url =>
This is a great application providing you fun in two different modes. 

*Bow and Arrow
Have you ever played Bow and Arrow on your personal computer, then its time to bring it on your iPhone too. Test the sharpness of your vision and shoot the target right in its middle. A good way to test your archery skills.

*Super Slots
Do you love gambling? Then why should waste your money when you can convert your iphone into a slot machine and bet virtual money without any hesitation.

3) LoveBirds (iTunes_url =>
This is a love matching tools which combines the compatibility test results from Chinese Astrology, Western Zodiac and Feng Shui Kua matches to deliver the most objective and accurate compatibility advice for people. The Love Bird Report(LBR) enables to tell people about their most compatible mates. This unique and revolutionary tool is great for people joining the dating services and looking for a long-lasting relationship.

Tuesday, February 24, 2009

iPhone Application Development

Starting the development of application for iphone is one of the toughest job, specially for a new programmer. I have been learning about it for past few weeks and now I want to share my experiences with you all.
By the way, I am going to provide you links of some very good sites that helps any novice developer a lot to overcome this steep learning curve.

It is the newest online iPhone SDK tutorial database offering FREE home-made tutorials made by people just like you who have a single goal as - to share as much information about developing for the iPhone SDK as possible. All tutorials are divided in three sections: Beginner, Intermediate and Advanced.


This site includes tutorials regarding various different aspects of iphone application starting from first iphone application and then gradually explaining UITabbars, UINavigation bars, single and multi touch, using SQLite for saving data, localization of iphone application, etc.


Sometimes people have a hard time writing their first application. It is easy to think that it will take too much time, and that it will be too hard. But that is simply not the case. But instead of telling people, this site shows them how easy it really is. This site contains codes of 31 simple applications. Someone considering writing their first iPhone application should be able to look at these applications and "get it".