Thursday 13 December 2012

How to Override Silent switch while playing sounds in an iPhone/iPad app using AVPlayer

As you guys know there are 2 ways to play sound files from the within app like game sounds, warning/caution sounds or alarm sounds.

One is by using Audio Services in AudioToolBox frame work.
And the other is by using AVPlayer in AVFoundation frame work.

You can follow How to play sounds in an iPhone/iPad app tutorial to learn how to play sounds in an iOS app.

The trick to override the switch is possible only by using AVPlayer, and here is how we can accomplish that.
Just use the below line, must be used in viewDidLoad or some where before using AVPlayer classes.

[[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryPlayback
error: nil];

How to play sounds in an iPhone/iPad app And Override Silent switch

As you guys know there are 2 ways to play sound files from the within app like game sounds, warning/caution sounds or alarm sounds.

One is by using Audio Services in AudioToolBox frame work.
And the other is by using AVPlayer in AVFoundation frame work.

Using AudioToolBox

In your header file, just import the class "AudioToolbox/AudioToolbox.h"
and declare a variable for the soundId, used to identify the sound and played at any instance.

SystemSoundID _soundId;


In your implementation file write the below method to create the soundId for the required sound file, usually call this method from viewDidLoad.


- (void) createSoundId
{
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"light_chime" ofType:@"mp3"];
if ([[NSFileManager defaultManager] fileExistsAtPath:soundPath])
{
NSURL* soundPathURL = [NSURL fileURLWithPath:soundPath];
AudioServicesCreateSystemSoundID((CFURLRef)soundPathURL, &_soundId);
}
}


And then its done, you can play for the created soundId as many times as you can using below code.

AudioServicesPlaySystemSound(_soundId);


Once the work is done, you need to disconnect or discard this soundId by using below line, you can also use it to stop playing the sound at any time while playing.

AudioServicesDisposeSystemSoundID(_soundId);


And remember once the soundId is disposed you need to create the soundId again in order to play the same sound again.

Using AVPlayer

There is one limitation using AudioToolBox, it plays sounds which have less then 30seconds duration. For sounds more than 30seconds duration, AVPlayer is the choice.

In your header file, just import the class "AVFoundation/AVFoundation.h"
And just use the below lines to play any sound using AVPlayer

NSString *soundPath = ResourcePath(kSoundName);
NSURL *soundFileURL = [NSURL fileURLWithPath:soundPath];
NSError* error1 ;
AVAudioPlayer * audioPalyer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: &error1];
if (nil == audioPalyer)
{
NSLog(@"Failed to play %@, %@", soundFileURL, error1);
return;
}
[audioPalyer prepareToPlay];
[audioPalyer setVolume:3];
[audioPalyer setDelegate:nil];
audioPalyer.numberOfLoops = 1;
[audioPalyer play];


And to override the silent switch just use the below line, must be used in viewDidLoad or some where before using AVPlayer classes.

[[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryPlayback
error: nil];


Download the working sample code here.

Happy coding.

Links Section

Hello developers, 

In the journey so far even i stuck up at some moments from days to weeks. Later on searching several forums and tutorials got solution to get through the difficulties easily. So in this section i will share the links of the blogs, forum's Q&A, tutorials which really helped me really a lot to fix my issues or get it done. 
And also some interesting links which i found.

HTMLParsing, as the name says i got a task to parse html content with in xml response to extract the content within. After some few search straight forward i got a tutorial which explained the steps beautifully, you all know the source of the tutorial, yes you are right its from Raywenderlich.                    

Orientations in iOS 6, as you all know apple changed its apis relate to orientations. I tried many options with the available new api's but none of them lead to success, finally got this tutorial from Shabbir's Forum, then everything worked like charm.

 GeoNames, The geographical database covers all countries and contains over eight million place names that are available for download free of charge. This provides the data in many formats so for newbie it will great site to learn parsing data from server, and more over it also has data in other formats too. Have a look at the GeoNamesWebServices Overview.

Creating Static Libraries For iOS, you might have seen some libraries in xcode such as "libxml2.2", and many more. These are static libraries, this tutorial helps you to create your own static libraries.

Simple XML to NSDictionary Converter, as the name indicates its a simple XML to dictionary converter.

Generate PDF programmatically in iPhone/iPad SDK, generating your own pdf through code.

Saving Layers, slice the images from any Photoshop file. Extract layers as png files and implement in your app.

CoreData Basics Part 7 – Search Bars, many of you have wondered how search display controller is help ful, this tutorial is about that. Apart from that it integrates with the your core data too using fetch controller.

 Icons Pedia, a free site to get png files artworks for your app. And also you can create the app using these free artworks as a prototype app and later you can show it to your designer to create the artworks for your own.

 ZooZ- In-App Payments, apple has its own in-app purchase, which does the payments from the users app store accounts as it is linked with users Credit Card info. Apple says the app must use apple's in-app purchase if it deals with digital content. If you are selling a physical goods, you may opt user directly pays you through his Debit/Credit card, Zooz is one such payment gate way enables the user to pay through Debit/Credit card from your app. It also has an option to pay through PayPal.

 Upload your App - Diawi - Development iOS Apps Wireless Installation, this enables to download the app directly to your device through device's browser. You can upload the build to this site and send the link to your client so that he can download the app directly to his device and start testing.

Base64Online - base64 decode and encode, encoding & decoding any image in base64 format, which is a string of characters. You can send this data to your server from device to upload image files. This link provides to encode & decode images into base64 formats online.


Happy Coding,
Vishy

Friday 30 November 2012

Beginner's Choice

My dear developers,

Am Vishwanath, started my career directly from learning Objective-C building iOS applications. Before this i was just aware of C and C++ languages only. Now i have over 2.8 years on Obj-C and 2.4 years on iOS SDK. Have built apps on iPhone, iPod and iPad applications.
So far in my journey i have learned some skills like-

  • Hands on features/services like MapKit, Location based services, Web services based, XML, JSON, PDF, Paypal, in-app Purchases, Core data, iCloud.
  • Hands on e-commerce applications, Social networking applications, Event based applications.
In my journey i have built lots of sample applications to learn different concepts, different frameworks. Just for learning my self. Have come across lots of hurdles- found solutions, tricks and tips to complete the tasks in a easier way.Using these experiences which i gained so far we can build simple applications just like that in no time, and can decide which will be best out of many ways to accomplish the tasks/hurdles building any applications.
  
Now i can say that am a Beginner's Level-2 in iOS development. So want to help my co-developers, who want to start a career in iOS development or Beginner's Level-1. So that you can cross these hurdles in no time and develop great applications in less time.

To start this i will be posting Tutorials, Tips, Tricks, to complete Tasks and many more in this blog. So subscribe to this blog & be in touch to save your time in development. These tips will be really helpful in real time while building apps in many ways, so just have look on it.

Tutorials

Tips

Tricks
This list will be growing on, so keep looking at it every day.

Apart from this if you have some of good blogs or tutorials posted by you, send me a mail/ add in comments with link & description i will share it over here so that it will be useful to many other developers.

If you come across some issues & want any help/guidance from me just add a comment will have a tutorial for that, showing at which time you faced the issue with a solution to that, even with the details of the developer who actually got this issue (if they want so).

You can also suggest or request on what next topics should be?

So keep looking, keep coding, keep developing.

Thanks

How to add custom fonts to your iOS app

To have well designed UI in any app, we need to have some thing different then any other apps. This may be in terms of images, colors, contents, fonts, text styles, way of presentation. And suppose if the Xcode doesn't have the required things which we required.

Here is a tip for how to add your own custom font to use in any iOS app just in 3 steps.

1) Add the font file to your resource bundle, the file extension will be “otf”. Here is a font file of STIXGeneral.

2) Add the font info in your application info.plist file, once added your info.plist file will look similar like below.









3) Then nothing, just use the font any where in your app as required. The one is shown below, similarly


[_myLabel setFont:[UIFont fontWithName:@”STIXGeneral” size:44]];


That's it now your UI shows your own custom font.

Thanks
Happy Coding.

Saturday 20 October 2012

How to make a check button in the application without using image

In iOS application Xcode does not have an object of check button, which is available only in Mac applications. We can create a check button in the application by using unicode string.
The unicode string for check mark button is : 2611
and unicode string for uncheck button is : 2610

Using this string we can have a check mark or uncheck mark in the application, which is used for different states in UIButton.
[_checkButton setTitle:[NSString stringWithString:@"\u2610"] forState:UIControlStateNormal];
[_checkButton setTitle:[NSString stringWithString:@"\u2610"] forState:UIControlStateHighlighted];
[_checkButton setTitle:[NSString stringWithString:@"\u2610"] forState:UIControlStateDisabled];
[_checkButton setTitle:[NSString stringWithString:@"\u2610"] forState:UIControlStateNormal];
[_checkButton setTitle:[NSString stringWithString:@"\u2611"] forState:UIControlStateSelected];

This code can be wrtiten in viewDidLoad, where the initialization is done. And the state can be changed in the action method of this button, as shown in below method.
- (IBAction) click:(UIButton*)sender
{
sender.selected = !sender.selected;
}

As we have to change the state to selected for check, this line will do the work for that.

To identify the check or uncheck of the button, we need to just check the selected state of the button wether its YES or NO.

Happy Coding.

How to make use of Digital Color Meter application in MAC


We have an application in our MAC called "DigitalColor Meter". We can use this application into our application to get the color code for RGB.
Steps:
1)   Open Digital Color Meter application in MAC, can use spot light for easy search.
2)   Keep the required mode to "RGB as Percentage"
3)   Using the mouse pointer go to the required color on the screen.
4)   Note down the RGB values in percentage.
5)   In our code you can use the method 
[UIColor colorWithRed:0.663 green:0.855 blue:0.341 alpha:1]

Convert percentage values into fractions. like 53.5% will become 0.535. Use the respective RGB values in the code, and alpha value must be 1.
Run the application, you will get the exact color required.
For HTML users
In the "DigitalColor Meter" application set the mode to "RGB As actual value, 8-bit", so that you can get the RGB value as decimal number from 0-255. Note this RGB numbers.
  
Use RGB-HEX to get the hexadecimal number of the required color by inserting these RGB values.
for example:
R - 85   G - 20   B - 30
required color in hexadecimal is : #55141E
You can use this hexadecimal value, to get the required color in html code.

Happy Coding.

Friday 19 October 2012

delegates in Objective C

What is a Delegate?
Technically speaking, a delegate is just an object that has been assigned by another object as the object responsible for handling events.

An example with real time situation:
A xyz office has some 5 counters, you will enter into office go to counter 1 and submit the some details etc. And the counter 1 will tell you to wait for some time and move to counter 3 to finish to get your work complete. In this case counter 3 is your delegate which handles your events, which is referred by counter 1. Here the same counter 1 may also be the delegate, to handle your events.

Why Delegate is required?
In one word we can define delegate as “Call-back”. Means after performing some task, who, why and how will handle the events.

What is the use of this Delegate?
While building any applications or projects delegates play a very important roles. In some situations some tasks should be performed out of the area and after finishing we should get to know the results, whether task is achieved or in progress or stopped. These statuses can be accessed by using the delegates.

Predefined Example:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@“Hello” message:@“This is an alert view” delegate:self cancelButtonTitle:@“OK” otherButtonTitles:nil];

The initializer of the UIAlertView class includes a parameter called the delegate. Setting this parameter to self means that the current object is responsible for handling all the events fired by this instance of the UIAlertView class. If you don’t need to handle events fired by this instance, you can simply set it to nil:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@“Hello”message:@“This is an alert view” delegate:nil cancelButtonTitle:@“OK” otherButtonTitles:nil];

If you have multiple buttons on the alert view and want to know which button was tapped, you need to handle the methods defined in the UIAlertViewDelegate protocol. You can either implement it in the same class in which the UIAlertView class was instantiated or create a new class to implement the method, like this:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog([NSString stringWithFormat:@“%d”, buttonIndex]);
}

To ensure that the alert view knows where to look for the method, create an instance of SomeClass and then set it as the delegate:

SomeClass *myDelegate = [[SomeClass alloc] init];

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@“Hello” message:@“This is an alert view” delegate:myDelegate cancelButtonTitle:@“OK” otherButtonTitles:@“Option 1”, @“Option 2”, nil];
[alert show];


How to create our own delegates?
To create your own delegate, first you need to create a protocol and declare the necessary methods, without implementing. And then implement this protocol into your header class where you want to implement the delegate or delegate methods.

A protocol must be declared as below:

@protocol ServiceResponceDelegate <NSObject>

- (void) serviceDidFailWithRequestType:(NSString*)error;
- (void) serviceDidFinishedSucessfully:(NSString*)success;

@end

This is the service class where some task should be done. It shows how to define delegate and how to set the delegate. In the implementation class after the task is completed the delegate's the methods are called.

@interface ServiceClass : NSObject
{
id <ServiceResponceDelegate> _delegate;
}

- (void) setDelegate:(id)delegate;
- (void) someTask;

@end


@implementation ServiceClass

- (void) setDelegate:(id)delegate
{
_delegate = delegate;
}

- (void) someTask
{
...
...
...
perform task
...
...
...
if (!success)
{
[_delegate serviceDidFailWithRequestType:@”task failed”];
}
else
{
[_delegate serviceDidFinishedSucessfully:@”task success”];
}
}
@end

This is the main view class from where the service class is called by setting the delegate to itself. And also the protocol is implemented in the header class.

@interface viewController: UIViewController <ServiceResponceDelegate>
{
ServiceClass* _service;
}

- (void) go;

@end



@implementation viewController

//
//some methods
//

- (void) go
{
_service = [[ServiceClass alloc] init];
[_service setDelegate:self];
[_service someTask];
}


That's it, and by implementing delegate methods in this class, control will come back once the operation/task is done.
If you liked this tutorial or found something wrong with it please let me know!
I would love to hear your experience with it.