Translate

Tuesday, April 17, 2012

Is Application Running on iPhone or iPod touch

If you ever need to know whether your application is running on an iPod touch or an iPhone, the answer is as close as this one line of code:

NSString *deviceType = [UIDevice currentDevice].model;

To get the model of the device as a localized string:

NSString *deviceType = [UIDevice currentDevice].modellocalizedModel;
NSLog(@"type: %@", deviceType);

One use could be to customize messages shown within your applications, for example:

float version = 1.1;
...
NSString *deviceType = [UIDevice currentDevice].model;
NSLog(@"Your %@ has version %2.1f of Today's Horoscope installed.",
deviceType, version);

Here’s the output from both of the code snippets is shown below:

Query the Battery State and Level of Charge

There are times when checking in on the battery status can be a good idea. The code that follows shows how to monitor battery states and levels (percent of charge) using methods in the UIDevice class.
Enable Battery Monitor

To query information regarding the iPhone battery status, you start by enabling battery monitoring through a call in the UIDevice class. With enabling active, you can then get the battery level and state (e.g. charging, discharging, etc):

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

[[UIDevice currentDevice] batteryLevel];
[[UIDevice currentDevice] batteryState];

Notification of Battery Changes

You can monitor on going battery changes by registering to receive notifications of battery level and status updates:

// Request to be notified when battery charge or state changes
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStatus) name:UIDeviceBatteryLevelDidChangeNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStatus) name:UIDeviceBatteryStateDidChangeNotification object:nil];

Changes in the battery level/state will result in a call to the method batteryStatus, where you can update a visual que or otherwise handle changes.
Display Battery Status

To test the battery status I’ve written a simply view controller that has nothing more than a textview, where the current status and level are displayed.

There are two relevant sections of code for this application, the first is within the loadView method where I setup a textview, enable battery monitoring and add observers for the two notifications I am interested in:

- (void)loadView
{
[self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];

// Setup the textview to display battery status
textViewStatus = [[UITextView alloc] initWithFrame:CGRectMake (20, 20, 280, 64)];
[textViewStatus setFont:[UIFont boldSystemFontOfSize:18.0]];
[textViewStatus setEditable:NO];
[textViewStatus setTextAlignment:UITextAlignmentCenter];
[[self view] addSubview:textViewStatus];

// Round the corners and set border color
[textViewStatus setBackgroundColor:[UIColor whiteColor]];
[[textViewStatus layer] setBorderColor:[[UIColor blueColor] CGColor]];
[[textViewStatus layer] setBorderWidth:2.3];
[[textViewStatus layer] setCornerRadius:15];
[textViewStatus setClipsToBounds: YES];

// Enable monitoring of battery status
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

// Print current status
[self batteryStatus];

// Request to be notified when battery charge or state changes
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStatus) name:UIDeviceBatteryLevelDidChangeNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStatus) name:UIDeviceBatteryStateDidChangeNotification object:nil];

}

The second method of interest is batteryStatus, which is the other end of the notification requests, that is, the method called via the OS when the battery status or level changes:

- (void)batteryStatus
{
NSArray *batteryStatus = [NSArray arrayWithObjects:
@"Battery status is unknown.",
@"Battery is in use (discharging).",
@"Battery is charging.",
@"Battery is fully charged.", nil];

if ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateUnknown)
{
[textViewStatus setText:[batteryStatus objectAtIndex:0]];
NSLog(@"%@", [batteryStatus objectAtIndex:0]);
}
else
{
NSString *msg = [NSString stringWithFormat:
@"Battery charge level: %0.2f%%\n%@", [[UIDevice currentDevice] batteryLevel] * 100,
[batteryStatus objectAtIndex:[[UIDevice currentDevice] batteryState]] ];

[textViewStatus setText:msg];
NSLog(@"%@", msg);
}
}

Notes

The battery status returned from the API’s above may not always be in sync with the status displayed on device – notice in the screenshot above that the device status is different than what is displayed in the textview (bug or feature, I’m not certain).

Also, Apple recommends that you enable battery monitoring only when your application needs to be notified of changes versus leaving enabling monitoring during the entire lifecycle of your app.

Xcode Project Source Code

Download Xcode Project: iphonedevelopertips.com/wp-content/uploads/2011/01/BatteryStatusIndicator.zip

Get iPhone Device Name, Unique Device Identifier (UDID), OS and Model

The iPhone SDK includes a singleton of class type UIDevice that you can use to retrieve device specific information (this works equally as well with the simulator).
Available Properties in UIDevice

uniqueIdentifier – identifier guaranteed to be unique for every device
name – arbitrary name found in General > About setting on device
systemName – name of the OS running on the device
systemVersion – current version of the OS
model- model, such as ”iPhone” or ”iPod touch”
localizedModel – same as above using a localized string

Stats for Simulator

This code will list all stats shown above:

NSLog(@"uniqueIdentifier: %@", [[UIDevice currentDevice] uniqueIdentifier]);
NSLog(@"name: %@", [[UIDevice currentDevice] name]);
NSLog(@"systemName: %@", [[UIDevice currentDevice] systemName]);
NSLog(@"systemVersion: %@", [[UIDevice currentDevice] systemVersion]);
NSLog(@"model: %@", [[UIDevice currentDevice] model]);
NSLog(@"localizedModel: %@", [[UIDevice currentDevice] localizedModel]);

Running the above on the simulator returns:

Stats for iPhone

The device stats when running on my iPhone:

Using the Proximity Sensor

The proximity sensor on the iPhone detects when the device is close to your face (or otherwise covered). There aren’t many times when using the sensor is of value, however, the Google Voice Search application has put this to good use as a means to trigger voice recording for a search request. If you have an interest in doing something similar, read on.
Proximity Sensor Monitoring

It all begins by enabling proximity monitoring, this is followed by setting up a notification request to call a method when the proximity state changes:

// Enabled monitoring of the sensor
[[UIDevice currentDevice] setProximityMonitoringEnabled:YES];

// Set up an observer for proximity changes
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sensorStateChange:)
name:@"UIDeviceProximityStateDidChangeNotification" object:nil];

The method below will be called when the sensor state is updated, a message is printed to the debug console based on the sensor proximity.

- (void)sensorStateChange:(NSNotificationCenter *)notification
{
if ([[UIDevice currentDevice] proximityState] == YES)
NSLog(@"Device is close to user.");
else
NSLog(@"Device is ~not~ closer to user.");
}

Detecting Proximity Sensor

Not all iOS device have proximity sensors. The Apple API documentation states that you should enable proximity monitoring and check the proximityState, if the return value is NO, then the device does not have a sensor.

I was unable to successfully use this approach to determine if a device has a sensor. Any additional ideas or suggestions are welcome.

Check If App Is Running On An iPad

Check the userInterfaceIdiom property of the device to get the information you need:

- (BOOL)isDeviceiPad
{
BOOL iPadDevice = NO;

// Is userInterfaceIdiom available?
if ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)])
{
// Is device an iPad?
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
iPadDevice = YES;
}

return iPadDevice;
}

As noted in the comments below, Apple provides a macro to accomplish the same task. Here is the full definition from the UIDevice.h header file:

#define UI_USER_INTERFACE_IDIOM() ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? [[UIDevice currentDevice] userInterfaceIdiom] : UIUserInterfaceIdiomPhone)

Count The Number of Words in a String

Here’s a quick way to count the number of words in an NSString object. The trick is to use the character set whitespaceAndNewlineCharacterSet which will look for spaces, tabs and newline characters.

- (NSUInteger)wordCount:(NSString *)str
{
NSUInteger words = 0;

NSScanner *scanner = [NSScanner scannerWithString: str];

// Look for spaces, tabs and newlines
NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
while ([scanner scanUpToCharactersFromSet:whiteSpace intoString:nil])
words++;

return words;
}

If you have another way to reach the same result, please post a code sample.

Writing a Flashlight Application using the iPhone LED

With the introduction of the iPhone 4, Apple has added an LED alongside the camera. It’s amazing how bright this little bugger is, ideal for a flashlight!

Since the release of the iPhone 4 I’ve been meaning to take a few minutes and write a flashlight application using the LED. My understanding from what I’ve gleaned from the API’s is that in order to turn on the LED, we need to essentially go through the same steps we would to capture video – if you know of a quicker and/or simpler process, please post some code below.
iPhone Flashlight UI

The user interface of this app is about as simple as they get – nothing more than a button to toggle the flashlight on and off.

The code for the UI is equally as trivial, in loadView, check if the device has a torch and if so, add a button to toggle the flashlight state.

- (void)loadView
{
[self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

// If torch supported, add button to toggle flashlight on/off
if ([device hasTorch] == YES)
{
flashlightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 120, 320, 98)];
[flashlightButton setBackgroundImage:[UIImage imageNamed:@"TorchOn.png"] forState:UIControlStateNormal];
[flashlightButton addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchUpInside];

[[self view] addSubview:flashlightButton];
}
}

Toggling the Flashlight On and Off

The event management code for this app is nothing more than swapping the button background image to reflect the current state of the flashlight followed by a call to the code that will toggle the LED on and off.

- (void)buttonPressed:(UIButton *)button
{
if (button == flashlightButton)
{
if (flashlightOn == NO)
{
flashlightOn = YES;
[flashlightButton setBackgroundImage:[UIImage imageNamed:@"TorchOff.png"] forState:UIControlStateNormal];
}
else
{
flashlightOn = NO;
[flashlightButton setBackgroundImage:[UIImage imageNamed:@"TorchOn.png"] forState:UIControlStateNormal];
}

[self toggleFlashlight];
}
}

AVCaptureSession Configuration

There are a few objects that we’ll need to interact with to get everything working. AVCaptureDevice is the object we’ll use to represent the physical video device. An AVCaptureSession object will manage the flow of data. And finally, AVCaptureDeviceInput will represent the video data.

With the objects above defined, we configure the AV session to set the torch on and start the session running…

- (void)toggleFlashlight
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

if (device.torchMode == AVCaptureTorchModeOff)
{
// Create an AV session
AVCaptureSession *session = [[AVCaptureSession alloc] init];

// Create device input and add to current session
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
[session addInput:input];

// Create video output and add to current session
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
[session addOutput:output];

// Start session configuration
[session beginConfiguration];
[device lockForConfiguration:nil];

// Set torch to on
[device setTorchMode:AVCaptureTorchModeOn];

[device unlockForConfiguration];
[session commitConfiguration];

// Start the session
[session startRunning];

// Keep the session around
[self setAVSession:session];

[output release];
}
else
{
[AVSession stopRunning];
[AVSession release], AVSession = nil;
}
}

Caveats

Stating the obvious, this application will only work on iPhone 4+ devices. Also, this application works on only on a device – you will receive compile time errors regarding AVCaptureSession if you attempt to build the app for the simulator.

One last thought – chances are running the LED for any length of time may give your battery a pretty intense workout. It may be worthwhile to keep an eye on your battery indicator if you plan to turn the light on for more than a few minutes.
iPhone LED Flashlight- Xcode Project

Here is the link to download the source code for the iPhone LED Flashlight application. iosdevelopertips.com/wp-content/uploads/2010/12/flashlightApp.zip

Submitting iPhone Apps To The Apple App Store – A Step by Step Guide

Here’s a quick step by step guideline that you can print and keep hand, to use when your app is ready for submission. I am assuming that the reader of this article has an iPhone Developer License.

Here’s a quick step by step guideline that you can print and keep hand, to use when your app is ready for submission. I am assuming that the reader of this article has an iPhone Developer License.

====== Step 1 ======

Certificate is an essential element to submit or test an application on iphone. It comes with code sign(Signatures) which would verified when an application is submitted on apple store or when tested on iphone.

One can bypass these if an application is installed on jail-break iphone or when submitted on Cydia but this is not possible when one wants submit it to Appstore.

One has to through 2 step procedure to create a certificate from developer portal. I simply copied those two from “iphone developer portal”

[1] Generating Certificate Signing Request

[2] Submitting a Certificate Signing Request for Approval

Generating a Certificate Signing Request:

[3] Open the Utilities folder and launch Keychain Access from the Applications folder.

[4] Set the value of Online Certificate Status Protocol (OCSP) and Certificate Revocation List (CRL) to “off” in the Preferences Menu.

[5] Select Keychain Access -> Certificate Assistant -> Request a Certificate from a Certificate Authority.

[6] Fill in your email address in User Email Address Field. Confirm that this email address is same as provided at the time of registering as iPhone developer.

[7] Fill in your name in the Common Name field. Confirm that this name is same as provided at the time of registering as iPhone developer.

[8] It is not necessary to have an Certificate Authority (CA). The ‘Required’ message would be eliminated after finishing the following step.

[9] Click the ‘save to disk’ radio button if prompted, choose ‘Let me specify key pair information’ and proceed.

[10] If you choose ‘Let me specify key pair’ option then one has provide a file name and click ‘Save’. Select ‘2048 bits’ for Key Size and ‘RSA’ for the algorithm in next screen and proceed.

[11] CSR file would created on the desktop by Certificate Authority.

Submitting a Certificate Signing Request for Approval:

[1] Once CSR file is created log in to the iPhone developer program portal and go to ‘Certificates’> ‘Development’ and select ‘Add Certificate’.

[2] Click the ‘Choose file’ button, select your CSR and click ‘Submit’. The portal will reject the CSR if Key Size is not set to 2048 bit at the time of CSR creation.

[3] This will followed by notification to Team Admins by email of the certificate request.

[4] The change in the certificate status would informed by email on approval or rejection of the CSR by Team Admin.

Download/Installing Certificate on your machine

[5] Once the CSR is approved the Team Members and Team Admins can download their certificates via the ‘Certification’ section of the Program Portal. Choose ‘Download’ next to the certificate name to download your iPhone development certificate to your local machine.

[6] Once this is done double-click the .cer file to launch Keychain Access and install your certificate.

On installation of certificate on your MAC the next step is to create an App ID.

Note: You have to follow this step only once and late you don’t have to make certificates for your other applications.

====== Step 2 ======

Follow the following steps to create an App ID:

[1] Go to ‘App IDs’ and click ‘App ID’ after logging in to iPhone developer program portal.

[2] Populate the ‘App Id Name’ field with your application name (that is – iPhone app) and in ‘App Id’ enter something like com.yourdomain.applicationname (i.e com.edumobile.iphoneapp) and click submit.

[3] Please do note down the “App Id” as this would be utilized in Info.plist, bundle identifier tag.

====== Step 3 ======

Next step would be to create a Provisioning file for our Xcode and is the last step for creating binary which would submit it to Appstore.

[1] After you navigate to ‘Provisioning’> ‘Distribution’ click ‘Add Profile’ in iphone developer program portal.

[2] Choose “App Store” in “Distribution Method”.

[3] In “Profile Name” enter your application name (i.e iphoneapp) which will be your provisioning profile name as well.

[4] In “App ID” select the app name(i.e. iphoneapp) which you created in Step 2.

[5] After downloading the Provisioning profile copy it to your/YourUserName/Library/MobileDevice/Provisioning Profile.

====== Step 4 ======

Now everything is step up, open your project in Xcode

[1] Click “i” Info button after selecting your project from “Group & File” in left side bar.

[2] Navigate to “Configuration” tab and select “Release”. Click the “Duplicate” button from bottom, name is “iphoneDistribution”.

[3] Click on “Build” tab and choose “iphoneDistribution” and enter in “Search in Build Settings” filed ‘Base SDK’ and select the current selected Device and change to what gadget your application is targeting (I prefer “Device-iPhone OS 2.0)

[4] Now in “Search in build setting” field enter “code signing identity” and choose the provisioning profile created earlier in Step 3. Apply the same to the child property “Any iPhone OS Device”.

[5] Once this done close the Info screen and select the “Target”> “Your App” from “Group & File” in left side bar and click on “Info” button again from Xcode.

[6] To be on the safer side repeat step 3 and 4.

[7] With the Info screen still open click on “Properties” tab and enter “App Id”(i.e. com.edumobile.iphoneapp) in Identifier field.

[8] Now that all is done, click on “Build” (cmd+B) from Xcode>Build.

[9] You will find your binary file created on right clicking on “Product”> “YourApp” and selecting “Reveal in Finder”. Zip this file.

====== Step 5 ======

The next step is to submit the binary file created to itunesconnect.

[1] In your browser type https://itunesconnect.apple.com/ (this website is very slow over https) and login using your iPhone developer account.

[2] Click on “Manage Your Account” > “Add Application”

[3] On replying to a simple question from apple you can sumbit your application to app store. You also need few things in your system before you submit your application.

a) Application Name (must be unique)

b) Application description

c) Application Category

d) URL for your application feedback.

e) Icon of your application in 512 x 512 size.

f) Main picture of your application in 320 x 480 or 320 x 460 size. (You have option to submit up to 4 more pictures of your application).

Tuesday, April 10, 2012

Implement iAds into your application

iAds are pretty cool to work with, and in todays session that's exactly what we are going to see.


What are iAd: iAd is a mobile advertising platform developed by Apple Inc. for its iPhone, iPod Touch, and iPad line of mobile devices allowing third-party developers to directly embed advertisements into their applications and you can make some revenu out of it.


Here's apples developer documentation on iAD Framework


How to add iAd in the release version: All the technical part is handled by apple in this link.


How to use iAd: Read the below blog silly


Here's a view at the final output that you will get








Step 1: Open Xcode and create an empty application with an XIB file and don't drag and drop anything into the XIB for now let it be empty.


Step 2: Add the iAd Framework into your application, here's what you have to do Select the XcodeProject File(one with the blue color) ->Target -> Build Phases -> Expand Link Binary -> Hit the plus button and add the iAdFramework






Step 3: Now its time to add some code, before coding we need to keep in mind that the ads are coming from the internet so their can be a senario where you don't have the internet so in that case hide the iAd view don't display it.
Don't worry to do this kind of implementation apple has already provided you with some delegate methods in which all you iOS developers can write code to hide the iAdview.


a) Lets create the iAdView: Import the AdBannerView in the .h file of your view controller



#import
#import

@interface MyiADViewController : UIViewController
{
ADBannerView *iadView;
BOOL ismyAdVisible;
}

//using it for animating the iADBannerView
@property (nonatomic,assign) BOOL ismyAdVisible;

- (void)createTheAdBannerView;

@end



Code Explanation: I am creating an object of the AdBanner class where you will be viewing the ads also the boolean variable is for the time when the network voids and you have to hide the Banner view.


The function createTheAdBannerView will create the Banner view and make it ready for the display.


And since we will be using the delegate methods of the ADBannerView class i have implemented the protocol for the same.


Let's have a look at the createTheAdBannerView function



- (void)createTheAdBannerView{

if (NSClassFromString(@"ADBannerView")) {
//making it live goes here
iadView = [[ADBannerView alloc]initWithFrame:CGRectZero];
iadView.frame = CGRectOffset(iadView.frame, 0, -50);
iadView.requiredContentSizeIdentifiers = [NSSet setWithObject:ADBannerContentSizeIdentifier320x50];
iadView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier320x50;
[iadView setDelegate:self];
self.ismyAdVisible = NO;
[self.view addSubview:iadView];

}
}

Code Explanation: First we check if the ADBannerView is present in the current SDK or not and if not then probably nothing will be displayed.


The second line of code will allocate the memory for the ADBannerView


Since we don't want to see the banner view on launch i am setting the frame accordingly.


The requiredContentSizeIdentifiers property will set the size for the ads that will appear in the ADBannerView


The currentContentSizeIdentifier property will set the size of the ADBannerView


And finally am setting the delegate to self and setting the boolean property to NO and after all the hard work is done am making the ADBannerView the subview of the current view.


Step 4: Now when the above code is set and in place lets code for the delegate methods, there are two delegate methods which we will be using the one to show the ad and the other to hide it when their is no network.



- (void)bannerViewDidLoadAd:(ADBannerView *)banner{

if (!self.ismyAdVisible) {
[UIView beginAnimations:@"animateAdBanner" context:NULL];
banner.frame = CGRectOffset(banner.frame, 0, 70);
[UIView commitAnimations];
self.ismyAdVisible = YES;
}
}



Code Explanation: Am animating it to display the AdbannerView



- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error{

if (self.ismyAdVisible) {
[UIView beginAnimations:@"animateAdBannerOff" context:NULL];
banner.frame = CGRectOffset(banner.frame, 0, -50);
[UIView commitAnimations];
self.ismyAdVisible = NO;
}
}

Code Explanation: I am hiding it when their is no internet with some simple animation.

Step 5: Select the AppDelegate.m file to add the viewcontrollers view inside the iPhone window

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
MyiADViewController *obj = [[MyiADViewController alloc]initWithNibName:@"MyiADViewController" bundle:nil];
[self.window addSubview:obj.view];
[self.window makeKeyAndVisible];
return YES;
}



Hit the run button and when you do you will get the output as below






And when you click the Test Advertisement probably you should see the the other view given below confirming that iAD is ready to be used in your project






Hope that you have understood the steps involved in using the iAd Framework into your project, in case of any questions or queries kindly mail me or enter you queries as a comment and i will get back to you.


The demo won't work if you have issues with you internet so if the Ads don't show up in the first place then check your net connection and try again


You can download the source file link : https://github.com/downloads/KRadix/CommonUtility/iADPoc.zip

Load a PDF File in the iPhone

In todays session we will learn how to launch a PDF file present in the server into our iPhone application.


For this you require the QuickLook Framework and its class called as the QLPreviewController. With the help of this class you can view documents like


a) iWork Documents
b) Microsoft Office Documents
c) RTF documents
d) PDF Files
e) Images
f) Text Files
g) CSV (Comma separated files)


For this tutorial i have just displayed PDF files, the file could be present any where in the server or in the app bundle. But since in maximum of the application the PDF files are loaded from the server i shall do the same in this demo.


Step 1: Open Xcode and create a view which looks like the one given below






Step 2: Add the Quick Look framework into your project and import it into your view controller.h file, create the object of the QLPreviewController in the table views did select row at index method and set its dataSource and delegate methods



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


//initializing the fileURL object with the URL links to be loaded
switch (indexPath.row) {
case 0:
fileURL = [NSURL URLWithString:kStringURLViewControllerPDF];
break;

case 1:
fileURL = [NSURL URLWithString:kStringURLQLPreviewControllerPDF];
break;
case 2:
fileURL = [NSURL URLWithString:kStringURLUIDocumentInteractionControllerPDF];
break;
}
//creating the object of the QLPreviewController
QLPreviewController *previewController = [[QLPreviewController alloc] init];

//settnig the datasource property to self
previewController.dataSource = self;

//pusing the QLPreviewController to the navigation stack
[[self navigationController] pushViewController:previewController animated:YES];
[previewController release];
}

Code Explanation: The maximum coding is very simple and is given in the comments i am initializing the fileURL object which is the object of NSURL class which will be returned in the QLPreviewController datasource later to load the pdf files/


Step 3: Add the QLPreviewController datasource method which will do all the hardwork for you and launch the PDF for you.



#pragma mark QLPreviewControllerDataSource


// Returns the number of items that the preview controller should preview
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)previewController
{
return 30;
}

// returns the item that the preview controller should preview
- (id)previewController:(QLPreviewController *)previewController previewItemAtIndex:(NSInteger)idx
{
return fileURL;
}



Code Explanation:


numberOfPreviewItemsInPreviewController: Invoked when the Quick Look preview controller needs to know the number of preview items to include in the preview navigation list. (required)


previewItemAtIndex: Invoked when the Quick Look preview controller needs the preview item for a specified index position. (required)

Step 4: Add the view into the iPhone window with the help of the navigation controller, and then add the navigation controller into the iPhone window to add navigation and in case if you dont want navigation you may skip the adding the navigation controller.


Step 5: Launch the application and view the PDF's








you may also zoom in and out and even print the PDF.


But it is advised to use the UIDocumentInteractionController but its a bit complex so i came up with this easy solution.


Download the source code link : https://github.com/downloads/KRadix/CommonUtility/SmoothDocumentLoaderProject.zip

Monday, April 9, 2012

Friday, April 6, 2012

How to play an audio file on launch of IOS application?


Apple provided a very good framework called 'AVFoundation' provides an Objective-C interface for  managing and playing the audio-visual media in your IOS applications.
Please follow the below steps to integrate the audio file to your project:
1. Add the 'AVFoundation.framework' to your frameworks folder in the project.
2. Add the statement  #import <AVFoundation/AVFoundation.h>
3. Add the file 'Output.aif' (an audio file) to your project.
4. Have the following snippet of code in your viewDidLoad method

    
NSString *path = [[NSBundle mainBundle] pathForResource:@"Output" ofType:@"aif"];  
    
AVAudioPlayer *theAudio = 
        [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];  
    
theAudio.delegate = self;  
    
[theAudio play];

5. Run the application. You will start listening the music.

Wednesday, April 4, 2012

Update Database

//#import <sqlite3.h>
//sqlite3 *database;


-(void)updateDatabase:(NSString*)bookTitle1 andauthor:(NSString*)bookAuthorName1 andid:(NSString*)bookId1{
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES);
    NSString *libraryDirectory=[paths objectAtIndex:0];
    NSString *databasepath1 = [libraryDirectory stringByAppendingPathComponent:@"database"];
   
    if(sqlite3_open([databasepath1 UTF8String], &database) == SQLITE_OK) {
        sqlite3_stmt *compiledStatement;
        const char *sql="UPDATE tbl_book Set fld_title=?,fld_author=? Where fld_id=?";          
        if (sqlite3_prepare_v2(database, sql, -1, &compiledStatement, NULL) != SQLITE_OK){
           
            NSAssert1(0, @"Error while creating update statement. '%s'", sqlite3_errmsg(database));
            if (SQLITE_DONE != sqlite3_step(compiledStatement))
                NSAssert1(0, @"Error while updating. '%s'", sqlite3_errmsg(database));
           
        }
        sqlite3_reset(compiledStatement);
        sqlite3_bind_text(compiledStatement, 1, [bookTitle1 UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(compiledStatement, 2, [bookAuthorName1 UTF8String], -1, SQLITE_TRANSIENT); 
        sqlite3_bind_int(compiledStatement, 3, [bookId1 intValue]);
       
        int success = sqlite3_step(compiledStatement);
        if (success == SQLITE_ERROR) {
            NSAssert1(0, @"Error: failed to insert into the database with message '%s'.", sqlite3_errmsg(database));
        }
        else{
            NSLog(@"Success");
            sqlite3_finalize(compiledStatement);
        }
        sqlite3_close(database);
    }
   
}

Monday, April 2, 2012

How to camera on in iphone sdk


.h File:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    IBOutlet UIButton *btn;
    IBOutlet UIImageView *imageView;
}
@property(nonatomic, retain) IBOutlet UIImageView *imageView;


@end






.m File:


- (void)picturePicker:(UIImagePickerControllerSourceType)theSource {
   
  
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
   
    picker.delegate = self;
    picker.sourceType = theSource;
    picker.allowsEditing = YES;
    
    [self presentModalViewController:picker animated:YES];
   
    [picker release];
}

- (IBAction) takePicture:(id)sender {
   
    if([UIImagePickerController isCameraDeviceAvailable: UIImagePickerControllerCameraDeviceRear] || [UIImagePickerController isCameraDeviceAvailable: UIImagePickerControllerCameraDeviceFront])
    {
         UIImagePickerControllerSourceType source = UIImagePickerControllerSourceTypeCamera;
   
         if ([UIImagePickerController isSourceTypeAvailable:source]) {
       
         [self picturePicker:source];
       
        }
    }
   
    else
    {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Message" message:@"There is no Camera on your device" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker
      didFinishPickingImage : (UIImage *)image
                 editingInfo:(NSDictionary *)editingInfo
{
    imageView.image = image;
   
    [picker dismissModalViewControllerAnimated:YES];
 }

   


  

WebView Application in iPhone

In this application we will see how to WebView display in the view window . So let see how it will worked.
Step 1: Open the Xcode, Create a new project using View Base application. Give the application “MapViewiPhone”.
Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.
Step 3: Expand classes and notice Interface Builder created the ViewController class for you. Expand Resources and notice the template generated a separate nib, MapViewiPhoneViewController.xib for the MapViewiPhone application.
Step 4: We need to add MapKit.framework in the Frameworks folder.
Step 5: Open the MapViewiPhoneViewController.h file and make the following changes:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface MapViewiPhoneViewController : UIViewController {
 
    IBOutlet MKMapView *map;
   
}
@property(nonatomic, retain) IBOutlet MKMapView *map; @end
Step 6: Double click the MapViewiPhoneViewController.xib file and open it to the Interface Builder. First drag the mapview from the library and place it to the View window. Connect File’s Owner icon to the view window and select map. Now save the .xib file, close it , and go back to the Xcode.
Step 7: Open the MapViewiPhoneViewController.m file and make the following changes:
#import "MapViewiPhoneViewController.h"
@implementation MapViewiPhoneViewController @synthesize map;
- (void)dealloc
{
    [super dealloc];
}
- (void)didReceiveMemoryWarning
{

    [super didReceiveMemoryWarning];
   
}
#pragma mark – View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
   
        map.mapType = MKMapTypeSatellite;
        map.mapType=MKMapTypeStandard;
       
}
- (void)viewDidUnload
{
    [super viewDidUnload];
   
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
Step 8: Now compile and run the application on the Simulator.



You can Download SourceCode from here MapViewiPhone

Programmatically Segmented Control in iPhone

In this application we will see how to implement Segmented Control programmatically in iPhone. So let see how it will
worked.
Step 1: Open the Xcode, Create a new project using View Base application. Give the application
“ProgrammaticallySegmentedControl”.
Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the
directory structure to check out the content of the directory.
Step 3: Expand classes and notice Interface Builder created the FirstViewController and SecondViewController class
for you. Expand Resources and notice the template generated a separate nib,
ProgrammaticallySegmentedControlViewController.xib for the ProgrammaticallySegmentedControl application.
Step 4: Open the ProgrammaticallySegmentedControlViewController.m file and make the following changes:

#import "programmaticallySegmentedControlViewController.h"
#define HeightSegmControl 40.0
#define TextHeight 30.0
#define LeftMargin 30.0
#define RightMargin 30.0
#define TweenMargin 30.0
@implementation programmaticallySegmentedControlViewController
- (void)SegmentControl
{
NSArray *text = [NSArray arrayWithObjects: @" Segmented", @"Control", @"iPhone", nil];
CGFloat yPlacement = (TweenMargin * 3.0) + HeightSegmControl;
CGRect frame=CGRectMake(LeftMargin, yPlacement, self.view.bounds.size.width-(RightMargin *
3.0),TextHeight);
UISegmentedControl *control= [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects: nil]];
control = [[UISegmentedControl alloc] initWithItems:text];
control.frame = frame;
//control.selectedSegmentIndex = 0;
[self.view addSubview:control];
[control release];
// label
//yPlacement += (mTweenMargin * 3.0) + mSegmentedControlHeight;
control = [[UISegmentedControl alloc] initWithItems:text];
frame = CGRectMake(LeftMargin,yPlacement,self.view.bounds.size.width-(RightMargin *
2.0),HeightSegmControl);
control.frame = frame;
control.segmentedControlStyle = UISegmentedControlStyleBar;
//control.tintColor = [UIColor colorWithRed:0.80 green:0.171 blue:0.5 alpha:1.0];
control.selectedSegmentIndex = 1;
[self.view addSubview:control];
[control release];
}
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn’t have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren’t in use.
}
#pragma mark – View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
[self SegmentControl];
}
- (void)segmentAction:(id)sender
{}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
 
 
Step 5: Now Compile and run the application on the Simulator.




You can Download SourceCode from here
 
 

Table View Application in iPhone

In this application we will see how to content delete , edit from the Table View. So let see how it will worked.
Step 1: Open the Xcode, Create a new project using View Base application. Give the application “TableView”.
Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.
Step 3: Expand classes and notice Interface Builder created the FirstViewController and SecondViewController
class for you. Expand Resources and notice the template generated a separate nib, TableViewViewController.xib for the TableView application.

Step 4: Open the TableViewAppDelegate.m file make the following changes:

#import "TableViewAppDelegate.h"
#import "TableViewViewController.h"
@implementation TableViewAppDelegate
@synthesize window=_window;
@synthesize viewController=_viewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)
launchOptions
{
UINavigationController *navController = [[UINavigationController alloc]
initWithRootViewController:_viewController];
[self.window addSubview:navController.view];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{}
- (void)applicationWillTerminate:(UIApplication *)application
{
}
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
@end
 
Step 5: Open the TableViewViewController.h file make the following changes:
#import <UIKit/UIKit.h>
@interface TableViewViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
IBOutlet UITableView *tableView1;
NSMutableArray *arry;
}
- (IBAction) EditTable:(id)sender;
@end
 
Step 6: Double click the TableViewViewController.xib file and open it to the Interface Builder. First drag the table view from the library and place it to the view window.Select the Table View from the view and bring up Connection Inspector and connect datasource to File’s owner icon and delegate to the File’s owner icon. Now save the .xib file, close it and go back to the Xcode.
Step 7: Open the TableViewViewController.m file make the following changes:

#import "TableViewViewController.h"
@implementation TableViewViewController
- (void)viewDidLoad
{
arry = [[NSMutableArray alloc]
initWithObjects:@"iPhone",@"MacMini",@"iMac",@"MacBookProAir",@"MacBookPro",nil];
self.title = @"Table View ";
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit"
style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)];
[self.navigationItem setLeftBarButtonItem:addButton];
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)dealloc
{
[super dealloc];
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int count = [arry count];
if(self.editing) count++;
return count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)
indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
int count = 0;
if(self.editing && indexPath.row != 0)
count = 1;
if(indexPath.row == ([arry count]) && self.editing)
{
cell.textLabel.text = @"ADD";
return cell;
}
cell.textLabel.text = [arry objectAtIndex:indexPath.row];
return cell;
}
- (IBAction)AddButtonAction:(id)sender
{
[arry addObject:@"MacBookPro "];
[tableView1 reloadData];
}
- (IBAction)DeleteButtonAction:(id)sender
{
[arry removeLastObject];
[tableView1 reloadData];
}
- (IBAction) EditTable:(id)sender
{
if(self.editing)
{
[super setEditing:NO animated:NO];
[tableView1 setEditing:NO animated:NO];
[tableView1 reloadData];
[self.navigationItem.leftBarButtonItem setTitle:@"Edit"];
[self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStylePlain];
}
else
{
[super setEditing:YES animated:YES];
[tableView1 setEditing:YES animated:YES];
[tableView1 reloadData];
[self.navigationItem.leftBarButtonItem setTitle:@"Done"];
[self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStyleDone];
}
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:
(NSIndexPath *)indexPath
{
if (self.editing == NO || !indexPath) return UITableViewCellEditingStyleNone;
if (self.editing && indexPath.row == ([arry count]))
{
return UITableViewCellEditingStyleInsert;
} else
{
return UITableViewCellEditingStyleDelete;
}
return UITableViewCellEditingStyleNone;
}
- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)
editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[arry removeObjectAtIndex:indexPath.row];
[tableView1 reloadData];
} else if (editingStyle == UITableViewCellEditingStyleInsert)
{
[arry insertObject:@"MacBookPro" atIndex:[arry count]];
[tableView1 reloadData];
}
}
#pragma mark Row reordering
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
@end
Step 8: Now Compile and run the application on the Simulator.

 you can download source code here: www.edumobile.org/iphone/wp-content/uploads/2011/09/TableView.zip






How to Receive data from the Server in iPhone

In this application we will see how to receive data from the server. This is the simple login application and when you login in the screen it will display the message, whatever we set in the server page. So let see how it will be worked.
In this application we will see how to receive data from the server. This is the simple login application and when you login in the screen it will display the message, whatever we set in the server page. So let see how it will be worked.
Step 1: Create a View base application using template. Give the application name “SendReceiveData”.
Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.
Step 3: Xpand classes and notice Interface Builder created the SendReceiveDataViewController class for you. Expand Resources and notice the template generated a separate nib, SendReceiveDatayViewController.xib, for the “SendReceiveData”.
Step 4: In the SendReceiveDataViewController.h file, we have added UITextField, UILabel, and one buttonClick method. So make the following changes in the file.
#import <UIKit/UIKit.h> @interface SendReceiveDataViewController :
UIViewController<UITextFieldDelegate> {
        IBOutlet UITextField *nameInput;
        IBOutlet UITextField *passInput;
        IBOutlet UILabel *greeting;
        NSMutableData *webData;
       
}
@property(nonatomic, retain) IBOutlet UITextField *nameInput;
@property(nonatomic, retain) IBOutlet UITextField *passInput;
@property(nonatomic, retain) IBOutlet UILabel *greeting;
@property(nonatomic, retain) NSMutableData *webData;
-(IBAction)buttonClick: (id) sender;
Step 5: Double click the SendReceiveDataViewController.xib file and open it to the Interface Builder. Drag three labels, one Round Rect Button and two TextField from the library and place it to the view window(See the figure below). Connect File’s Owner icon to the view icon and select view and drag File’s Owner icon to the “Input Your Values” and select greeting . Next drag File’s Owner icon to the first text field and select nameInput,do the same thing for the next text field and select passInput. Select the login button and bring up Connection Inspector and drag TouchUpInside to the File’s Owner icon and select buttonClick: action. Now save the SendReceiveDataViewController.xib file, close it and go back to the Xcode.

Step 6: Open the SendReceiveDataViewController.m file and make the following changes in the file:
-(IBAction)buttonClick:(id)sender
{
       
        NSString* username = nameInput.text;
        NSString* pass = passInput.text;
       
        if([nameInput.text isEqualToString:@"" ]|| [passInput.text isEqualToString:@""])
        {
               
                greeting.text = @"Input Your Value";
                [nameInput resignFirstResponder];
                [passInput resignFirstResponder];
                return;
        }
       
        NSString *post =
        [[NSString alloc] initWithFormat:@"uname=%@&pwd=%@",username,pass];
       
        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
       
        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
       
        NSURL *url = [NSURL URLWithString:@"http://www.chakrainteractive.com/mob/iphone/login/chckusr.php"];
        NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
        [theRequest setHTTPMethod:@"POST"];
        [theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [theRequest setHTTPBody:postData];     
       
       
        NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
       
        if( theConnection )
        {
                webData = [[NSMutableData data] retain];
        }
        else
        {
               
        }
       
        [nameInput resignFirstResponder];
        [passInput resignFirstResponder];
        nameInput.text = nil;
        passInput.text = nil;
       
} -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
        [webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
       
       
        [webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
       
        [connection release];
        [webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
       
        NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
        NSLog(loginStatus);
        greeting.text = loginStatus;
        [loginStatus release];
       
       
       
        [connection release];
        [webData release];
}
Step 7: Now compile and run the application in the Simulator.