09 August, 2010

Implementing Login authentication

In my example I have two text fields like below:
mUserNameTextField : Where user can enter his user name.
mPassWordTextField : Where user can enter his password.


Sending request to server:
First we need to create NSURLRequest, and use NSURLConnection to talk to your server.
NSString *urlStr = [NSString stringWithFormat:@"?username=%@&password=%@", mUserNameTextField.text, mPassWordTextField.text];
NSURL *url = [[NSURL alloc] initWithString:urlStr]; 
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
NSHTTPURLResponse* response = nil; 
NSError* error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];


Authentication response can be in two forms:
1) get the response in resposeData variable (returned from sendSynchronousRequest).
2) Write response data to some XML file in your server then read that response from your server.
In this example I am using second method.


Reading data from server:

NSString *urlStr = [NSString stringWithFormat:@"/uservalidation.xml"];
NSURL *url = [[NSURL alloc] initWithString:urlStr]; 
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
NSHTTPURLResponse* response = nil; 
NSError* error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];


After reading the data from server you can parse ti and then do necessary things:
NSXMLParser* results = [[NSXMLParser alloc] initWithData:responseData];
[results setDelegate:self];
[results parse];

25 March, 2010

Mac OS X Tips


Change the minimize effect in Mac OS X

When you click the yellow minimize button in Mac OS X, the snazzy Genie effect pulls the window into the Dock. Although you can change between the Genie and Scale effect from within the Dock preference pane, there is a third hidden effect that Apple has chosen to keep out of the preference pane. The hidden effect is named ‘Suck’, it’s more attractive than the Scale effect, and speedier than the Genie effect, here’s how to activate it:

To change the minimize effect to any of the three options, type or paste one of the following commands into the Terminal:
Suck effect (hidden from users)
defaults write com.apple.dock mineffect -string suck
Scale effect
defaults write com.apple.dock mineffect -string scale
Genie effect (Mac OS X Default)
defaults write com.apple.dock mineffect -string genie
Finally, to activate any of the above settings, you’ll need to reload the Dock by killing it:killall Dock
Your Dock will momentarily disappear and reappear, with the new minimize effect activated.

20 January, 2010

Tricks

Trick1: When I implemented my custom ipod player in my game I have scheduled a timer to update playback duration(using UILabel), it worked fine but when I started playing game I saw a huge frame rate drop.I found that it is because my timer but it took me 3 hours to have a mechanism to start timer before displaying view and to stop the timer while going to another view.
Trick here is we have to call invalidate(to stop timer) in the same thread.And we can fire a new timer from any where so my final code was like this


-(void) stopPlayBackTimer
{
stopMyTimer = true;
}

-(void) startPlayBackTimer
{
playBackTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateSongPlayBack:) userInfo:nil repeats:YES];
}

-(void) updateMusicPlayerProgress
{
if(stopMyTimer)
{
stopMyTimer = false;
[playBackTimer invalidate];
playBackTimer = nil;
}
MPMediaItem* currentMediaIte = [musicPlayer nowPlayingItem];
long currentPlayBackTime = [musicPlayer currentPlaybackTime];
long totalPlayBackTime = [[currentMediaIte valueForProperty:MPMediaItemPropertyPlaybackDuration] longValue];
float progress = (float)currentPlayBackTime/totalPlayBackTime;
[songProgressIndicator setValue:progress animated:YES];
}

16 January, 2010

Using iPod Library



YOU APPLICATION -------------->     MUSIC PLAYER(music play back)
          |                   |
MEDIA PICKER MEDIA QUERY
                 |         |
iPod Library
(data base access)


Music Player :
There are 2 flavors of music players available:


  1. Application music player : Plays music locally within your application.It does not effect built in iPod app
  2. iPod music player : In effect,employes the built-in ipod app on your behalf.When auger quits an app that is using this player,the music continues to play.


Creating iPodMusicPlayer:
MPMusicPlayerController* iPodMusicPlyer = [MPMusicPlyerController iPodMusicPlayer];


Data base access:
2 ways to retrieve items(data base access)


  1. The media item picker : It is an easy to use, pre-packaged view controller that behaves like the built-in iPod application's music selection interface.
  2. The media Query : To provide the specialized access control that you want, the media query interface.


Using the Media Item Picker:
MPMediaPickerController : It is a specialized view controller that you employ to provide a graphical interface for selecting media items.To respond to user selections and to dismiss a media item picker, use the MPMediaPickerControllerDelegate protocol.
MPMediaPickerControllerDelegate protocol : The delegate for a media item picker can respond to a user making media item selections.The delegate is also responsible for dismissing the media item picker from the parent view controller.
Steps for using media item picker:
  1. Designate a controller object as a delegate of the picker.
  2. Invoke the picker from the controller.
  3. When the use indicates that they are finished, the delegate receives the chosen collection of media items and dismiss the picker.


STEP1 : Add the protocol name in the interface declaration.


@interface myController : UIViewController { // interface declaration
}


STEP2 : Invoke the picker from controller


  1. Create a media item picker .MPMediaPickerController* picker = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeAnyAudio];
  2. Establishes your controller objects the delegate.[picker setDelegate:self];
  3. Specifies the user can pick multiple items. [picker setAllowsPickingMultipleItems: YES];
  4. Optional setting A prompt, for user,that appears above the navigation bar.picker.prompt = NSLocalizedString(@"Add songs to play",@"prompt in media item picker");
  5. Display the picker.[self presentModalViewController:picker animated: YES];[picker release];


STEP3 : Implement 2 delegate methods("mediaPicker:didPickMediaItems:"  and "mediaPickerDidCancel") to suspend picker controller.


Useful methods:
mediaPicker:didPickMediaItems:
Called when a user has selected a set of media items.
- (void)mediaPicker: (MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
mediaPickerDidCancel:
Called when a user dismisses a media item picker by tapping Cancel.
- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker


[self dismissModalViewControllerAnimated:YES]


Updating playback :
Code here is self explanatory.

- (void) updatePlayerQueueWithMediaCollection: (MPMediaItemCollection *) mediaItemCollection {

// Configure the music player, but only if the user chose at least one song to play
if (mediaItemCollection) {

// If there's no playback queue yet...
if (userMediaItemCollection == nil) {

// apply the new media item collection as a playback queue for the music player
[self setUserMediaItemCollection: mediaItemCollection];
[musicPlayer setQueueWithItemCollection: userMediaItemCollection];
[musicPlayer play];

// Obtain the music player's state so it can then be
// restored after updating the playback queue.
} else {

// Take note of whether or not the music player is playing. If it is
// it needs to be started again at the end of this method.
BOOL wasPlaying = NO;
if (musicPlayer.playbackState == MPMusicPlaybackStatePlaying) {
wasPlaying = YES;
}

// Save the now-playing item and its current playback time.
MPMediaItem *nowPlayingItem = musicPlayer.nowPlayingItem;
NSTimeInterval currentPlaybackTime = musicPlayer.currentPlaybackTime;

// Combine the previously-existing media item collection with the new one
NSMutableArray *combinedMediaItems = [[userMediaItemCollection items] mutableCopy];
NSArray *newMediaItems = [mediaItemCollection items];
[combinedMediaItems addObjectsFromArray: newMediaItems];

[self setUserMediaItemCollection: [MPMediaItemCollection collectionWithItems: (NSArray *) combinedMediaItems]];
[combinedMediaItems release];

// Apply the new media item collection as a playback queue for the music player.
[musicPlayer setQueueWithItemCollection: userMediaItemCollection];

// Restore the now-playing item and its current playback time.
musicPlayer.nowPlayingItem = nowPlayingItem;
musicPlayer.currentPlaybackTime = currentPlaybackTime;

// If the music player was playing, get it playing again.
if (wasPlaying) {
[musicPlayer play];
}
}
}
}



13 January, 2010

Playing Sound Effects using OpenAL

Audio Optimizations:
          The iPhone and iPod touch devices are audio devices, but actually they dont have awesome audio hardware and most of the audio processing is actually done in software.
Playing Sound Effects inefficient way:
          There are many ways to play sound effects on the iPhone, but OpenAL provides the most optimized method for playing multiple channels of sound effects.
          In OpenAL a sound effect is stored in buffer and then played when needed.The format of this buffer is critical, because you dont want the CPU to have to do any extra work converting the hundreds and thousands of samples every second from the buffers format to Core Audio's native format[Core Audio File Format(CAFF)].
          You should never have some of your sounds to be 22kHz and some 44.1kHz.They must all be the exact same frequency, bit depth, and format, and the must be mono.Even having just one oddball effect can destroy the audio pipeline and cause serious performance issues.
          Note : The most optimal format for your CAFF files is 16bit at 44.1kHz since this is native format for the device.
          You can even use 16/22kHz to reduce burdon on RAM.In this case what core auido does is mixes all of your effects together into a single 16/22kHz buffer and then make a single pass to convert the data to the device's native 16/44.1 format(which requires a little extra CPU processing).

Using afconvert command line tool(in terminal app):
To generate a 16-bit/44.1kHz CAFF file, enter following:
         afconvert -f caff -d LEI16 {INPUT PATH} {OUTPUT PATH}
To generate a 16bit/22kHz file enter following:
         afconvert -f caff -d LEI16@22050 {INPUT PATH} {OUTPUT PATH}


There three fundamental objects in OpenAL:


  • Buffers : A buffer can be filled with audio data, and can then be attached to a source.
  • Sources : A source can be positioned and played.
  • Listener : Listener determines how the source is heard,by its position and orientation relative to the Listener object.



Creating 3D audio world in OpenAL:
      Create a number of sources and buffers and a single listener object and then updating the positions and orientations of the sources and listener dynamically can present a convincing 3D audio world.
Initializing OpenAL:
      At least one device has to be opened. Within that device at least one context will be created. Within that context, one listener object is implied, and a multitude of source objects can be created.Each source can have one or more buffer objects attached to it.
STEPS:

  • Open a device.
  • Open the context of that device,make it current context.
  • Create buffers and put some data into it.
  • Create source and attach buffer to source.
  • Play the source.
Reading the audio file data involves in 3 steps:

  • Create a AudioFileID using AudioFileOpenURL.
  • Get the audio file size using AudioFileGetProperty.
  • Using AudioFileID which we have created in step one finally read bytes using method AudioFileReadBytes.

Note : At runtime you can update source and listener properties to create a 3D audio world.

Method that are used for playing  sound effects with OpenAL:
alcOpenDevice : This takes a string as input.which is either the name of a valid OpenAL rendering device, or NULL to request the default device.
ALCdevice *alcOpenDevice(
const ALCchar *devicename
);
alcCreateContext : function creates the context with specified device
ALCcontext * alcCreateContext(
ALCdevice *device,
ALCint* attrlist
);
device : a pointer to a device
attrlist : a pointer to a set of attributes
ALC_FREQUENCY
ALC_MONO_SOURCES
ALC_REFRESH
ALC_STEREO_SOURCES
ALC_SYNC
alGenBuffers : this is used to generate the number of buffers desired.
void alGenBuffers(
ALsizei n,
ALuint *buffers
);
alBufferData : fills the buffers with audio data.
void alBufferData(
ALuint buffer,
ALenum format,
const ALvoid *data,
ALsizei size,
ALsizei freq
);
buffer : buffer name to be filled with data.
format : format type from among the following: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8, AL_FORMAT_STEREO16.
data : pointer to the audio data.
size : size of the audio data in bytes.
freq. : the frequrnce of the audio data.
alGenSource: generates the number of sources desired.
alSourcei : This function sets an integer property of a source.
void alSourcei(
ALuint source,
ALenum param,
ALint value
);
source : source name whose attribute is being set.
param : the name of the attribute to set: AL_SOURCE_RELATIVE, AL_CONE_INNER_ANGLE,AL_CONE_OUTER_ANGLE,AL_LOOPING,AL_BUFFER,AL_SOURCE_STATE.
value : the value to set the attribute to.
alSourcePlay : plays the buffer using source.
alGetListenerfv, alListener3f, alSourcei, alGetSource3f : these are the methods that allows you to updated Source and listener properties dynamically.
AudioFileReadBytes : Reads bytes of audio data from an audio file.
OSStatus AudioFileReadBytes{
AudioFileID inAudioFile,
Boolean inUseCache,
SInt64 inStartingByte,
UInt32* ioNumBytes,
void* outBuffer
};
inAudioFile : The audio file whose bytes of data you want to read.
inUseCache : decides read or write data caching.
inStartingByte : the byte offset of the audio data you want to be returned.
inNumBytes : on input, a pointer to the number of bytes to read.On output, a pointer to the number of bytes actually read.
outBuffer : a pointer to user-allocated memory large enough for the requested bytes.
AudioFileOpenURL : Open an existing audio file specified by a URL.
OSStatus AudioFileOpenURL(
CFURLRef inFileRef,
SInt8 inPermissions,
AudioFileTypeID inFileTypeHint,
AudioFileID * outAudioFile
);
inFileRef : The URL of an existing audio file.
inPermissions : The read-write permissions you want to assign to the file(kAudioFileReadPermission, kAudioFileWritePermission, kAudioFileReadWritePermission).
inFileTypeHint : Use this to hint to indicated the file type,otherwise, pass 0.
outAudioFile : A pointer to the newly opened audio file.
AudioFileGetProperty:
Gets the value of an audio file property.
OSStatus AudioFileGetProperty(
AudioFileID inAudioFile,
AudioFilePropertyID inPropertyID,
UInt32 *ioDataSize,
void *outPropertyData
);
inAudioFile : The audio file you want to obtain a property value from.
inPropertyID : The property whose value you want.\
ioDataSize : On input, the size of the buffer passed in the outPropertyData parameter. On output, the number of bytes written to the buffer.
outPropertyData : On output, the value of the property specified in the inPropertyID parameter.