iOS – iAd Integration iAd is used to display ads, served by the apple server. iAd helps us in earning revenue from an iOS application. iAd Integration – Steps Involved Step 1 − Create a simple view-based application. Step 2 − Select your project file, then select targets and then add iAd.framework in choose frameworks. Step 3 − Update ViewController.h as follows − #import <UIKit/UIKit.h> #import <iAd/iAd.h> @interface ViewController : UIViewController<ADBannerViewDelegate> { ADBannerView *bannerView; } @end Step 4 − Update ViewController.m as follows − #import “ViewController.h” @interface ViewController () @end @implementation ViewController – (void)viewDidLoad { [super viewDidLoad]; bannerView = [[ADBannerView alloc]initWithFrame: CGRectMake(0, 0, 320, 50)]; // Optional to set background color to clear color [bannerView setBackgroundColor:[UIColor clearColor]]; [self.view addSubview: bannerView]; } – (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark – AdViewDelegates -(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error { NSLog(@”Error loading”); } -(void)bannerViewDidLoadAd:(ADBannerView *)banner { NSLog(@”Ad loaded”); } -(void)bannerViewWillLoadAd:(ADBannerView *)banner { NSLog(@”Ad will load”); } -(void)bannerViewActionDidFinish:(ADBannerView *)banner { NSLog(@”Ad did finish”); } @end Output When we run the application, we”ll get the following output − Learn online work project make money
Category: ios
iOS – File Handling
iOS – File Handling ”; Previous Next File handling cannot be explained visually with the application and hence the key methods that are used for handling files are explained below. Note that the application bundle only has read permission and we won’t be able to modify the files. You can anyway modify the documents directory of your application. Methods used in File Handling The methods used for accessing and manipulating the files are discussed below. Here we have to replace FilePath1, FilePath2 and FilePath strings to our required full file paths to get the desired action. Check if a File Exists at a Path NSFileManager *fileManager = [NSFileManager defaultManager]; //Get documents directory NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0]; if ([fileManager fileExistsAtPath:@””]==YES) { NSLog(@”File exists”); } Comparing Two File Contents if ([fileManager contentsEqualAtPath:@”FilePath1″ andPath:@” FilePath2″]) { NSLog(@”Same content”); } Check if Writable, Readable, and Executable if ([fileManager isWritableFileAtPath:@”FilePath”]) { NSLog(@”isWritable”); } if ([fileManager isReadableFileAtPath:@”FilePath”]) { NSLog(@”isReadable”); } if ( [fileManager isExecutableFileAtPath:@”FilePath”]) { NSLog(@”is Executable”); } Move File if([fileManager moveItemAtPath:@”FilePath1″ toPath:@”FilePath2″ error:NULL]) { NSLog(@”Moved successfully”); } Copy File if ([fileManager copyItemAtPath:@”FilePath1″ toPath:@”FilePath2″ error:NULL]) { NSLog(@”Copied successfully”); } Remove File if ([fileManager removeItemAtPath:@”FilePath” error:NULL]) { NSLog(@”Removed successfully”); } Read File NSData *data = [fileManager contentsAtPath:@”Path”]; Write File [fileManager createFileAtPath:@”” contents:data attributes:nil]; Print Page Previous Next Advertisements ”;
iOS – Getting Started
iOS – Getting Started ”; Previous Next General Overview iOS, which was previously called iPhone OS, is a mobile operating system developed by Apple Inc. Its first release was in 2007, which included iPhone and iPod Touch. iPad (1st Generation) was released in April 2010 and iPad Mini was released in November 2012. The iOS devices get evolved quite frequently and from experience, we find that at least one version of iPhone and iPad is launched every year. Now, we have iphone5 launched which has its predecessors starting from iPhone, iPhone 3gs, iPhone 4, iPhone 4s. Similarly, iPad has evolved from iPad (1st Generation) to iPad (4th Generation) and an additional iPad Mini version. The iOS SDK has evolved from 1.0 to 6.0. iOS 6.0, the latest SDK is the only officially supported version in Xcode 4.5 and higher. We have a rich Apple documentation and we can find which methods and libraries can be used based on our deployment target. In the current version of Xcode, we’ll be able to choose between deployment targets of iOS 4.3, 5.0 and 6.0. The power of iOS can be felt with some of the following features provided as a part of the device. Maps Siri Facebook and Twitter Multi-Touch Accelerometer GPS High end processor Camera Safari Powerful APIs Game center In-App Purchase Reminders Wide Range of gestures The number of users using iPhone/iPad has increased a great deal. This creates the opportunity for developers to make money by creating applications for iPhone and iPad the Apple”s App Store. For some one new to iOS, Apple has designed an application store where the user can buy apps developed for their iOS devices. A developer can create both free and paid apps to App Store. To develop applications and distribute to the store, the developer will require to register with iOS developer program which costs $99 a year and a Mac with Mountain Lion or higher for its development with latest Xcode. Registering as an Apple Developer An Apple ID is most necessary if you are having any Apple device and being a developer, you definitely need it. It”s free and hence, no issues in having one. The benefits of having an Apple account are as follows − Access to development tools. Worldwide Developers Conference (WWDC) videos. Can join iOS developer program teams when invited. To register an Apple account, follow the steps given below − Step 1 − Click the link https://developer.apple.com/programs/register/ and select “Create Apple ID” Step 2 − Provide the necessary information, which is self explanatory as given in the page. Step 3 − Verify your account with your email verification and the account becomes active. Step 4 − Now you will be able to download the developer tools like Xcode, which is packaged with iOS simulator and iOS SDK, and other developer resources. Apple iOS Developer Program The first question that would arise to a new developer is – Why should I register for an iOS developer program? The answer is quite simple; Apple always focuses on providing quality applications to its user. If there was no registration fee, there could be a possibility of junk apps being uploaded that could cause problems for the app review team of Apple. The benefits of joining the iOS developer program are as follows − Run the apps you develop on the real iOS device. Distribute the apps to the app store. Get access to the developer previews. The steps to join the iOS developer program are as follows − Step 1 − To register, click on the link − (https://developer.apple.com/programs/ios/). Step 2 − Click on Enroll Now in the page that is displayed. Step 3 − You can either sign in to your existing apple account (if you have one) or create a new Apple ID. Step 4 − Thereafter, you have to select between Individual and Company accounts. Use company account if there will be more than one developer in your team. In individual account, you can”t add members. Step 5 − After entering the personal information (for those who newly registers), you can purchase and activate the program by paying with the help of your credit card (only accepted mode of payment). Step 6 − Now you will get access to developer resources by selecting the member center option in the page. Step 7 − Here you will be able to do the following − Create provisioning profiles. Manage your team and devices. Managing application to app store through iTunes Connect. Get forum and technical support. Print Page Previous Next Advertisements ”;
iOS – Accessing Maps
iOS – Accessing Maps ”; Previous Next Maps are always helpful for us to locate places. Maps are integrated in iOS using the MapKit framework. Steps Involved Step 1 − Create a simple view-based application. Step 2 − Select your project file, then select targets and then add MapKit.framework. Step 3 − We should also add Corelocation.framework. Step 4 − Add a MapView to ViewController.xib and create an ibOutlet and name it as mapView. Step 5 − Create a new file by selecting File → New → File… → select Objective C class and click next. Step 6 − Name the class as MapAnnotation with “sub class of” as NSObject. Step 7 − Select create. Step 8 − Update MapAnnotation.h as follows − #import <Foundation/Foundation.h> #import <MapKit/MapKit.h> @interface MapAnnotation : NSObject<MKAnnotation> @property (nonatomic, strong) NSString *title; @property (nonatomic, readwrite) CLLocationCoordinate2D coordinate; – (id)initWithTitle:(NSString *)title andCoordinate: (CLLocationCoordinate2D)coordinate2d; @end Step 9 − Update MapAnnotation.m as follows − #import “MapAnnotation.h” @implementation MapAnnotation -(id)initWithTitle:(NSString *)title andCoordinate: (CLLocationCoordinate2D)coordinate2d { self.title = title; self.coordinate =coordinate2d; return self; } @end Step 10 − Update ViewController.h as follows − #import <UIKit/UIKit.h> #import <MapKit/MapKit.h> #import <CoreLocation/CoreLocation.h> @interface ViewController : UIViewController<MKMapViewDelegate> { MKMapView *mapView; } @end Step 11 − Update ViewController.m as follows − #import “ViewController.h” #import “MapAnnotation.h” @interface ViewController () @end @implementation ViewController – (void)viewDidLoad { [super viewDidLoad]; mapView = [[MKMapView alloc]initWithFrame: CGRectMake(10, 100, 300, 300)]; mapView.delegate = self; mapView.centerCoordinate = CLLocationCoordinate2DMake(37.32, -122.03); mapView.mapType = MKMapTypeHybrid; CLLocationCoordinate2D location; location.latitude = (double) 37.332768; location.longitude = (double) -122.030039; // Add the annotation to our map view MapAnnotation *newAnnotation = [[MapAnnotation alloc] initWithTitle:@”Apple Head quaters” andCoordinate:location]; [mapView addAnnotation:newAnnotation]; CLLocationCoordinate2D location2; location2.latitude = (double) 37.35239; location2.longitude = (double) -122.025919; MapAnnotation *newAnnotation2 = [[MapAnnotation alloc] initWithTitle:@”Test annotation” andCoordinate:location2]; [mapView addAnnotation:newAnnotation2]; [self.view addSubview:mapView]; } // When a map annotation point is added, zoom to it (1500 range) – (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views { MKAnnotationView *annotationView = [views objectAtIndex:0]; id <MKAnnotation> mp = [annotationView annotation]; MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance ([mp coordinate], 1500, 1500); [mv setRegion:region animated:YES]; [mv selectAnnotation:mp animated:YES]; } – (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end Output When we run the application, we”ll get the output as shown below − When we scroll the map up, we will get the output as shown below − Print Page Previous Next Advertisements ”;
iOS – Application Debugging
iOS – Application Debugging ”; Previous Next We may commit mistakes while developing an application, which can lead to different kinds of errors. In order to fix these errors or bugs, we need to debug the application. Selecting a Debugger Xcode has two debuggers namely, GDB and LLDB debuggers. GDB is selected by default. LLDB is a debugger that is a part of the LLVM open-source compiler project. You can change the debugger by “edit active schemes” option. How to Find Coding Errors? To locate coding-related errors, you need to build your application which will compile the code. In case the code contains errors, the compiler will display all the messages, errors, and warnings with their possible reasons. You can click Product and then Analyze to locate possible issues in an application. Set Breakpoints Breakpoints help us to know the different states of our application objects, which help us identifying many flaws including logical issues. We just need to click over the line number to create a breakpoint. To remove a breakpoint, simply click and drag it out. The following screenshot shows how to set a breakpoint − When we run the application and select the playVideo button, the application will pause at the line number where we had set the breakpoint. It allows us the time to analyze the state of the application. When the breakpoint is triggered, we will get an output as shown below. You can easily identify which thread has triggered the breakpoint. In the bottom, you can see objects like self, sender and so on, which hold the values of the corresponding objects and we can expand some of these objects, and see what is the state of each of these objects. To continue the application we will select the continue button (left most button), in the debug area shown below. The other options include step in, step out and step over. Exception Breakpoint We also have exception breakpoints that trigger an application to stop at the location where the exception occurs. We can insert exception breakpoints by selecting the + button after selecting the debug navigator. You will get the following window. Then we need to select Add Exception Breakpoint, which will display the following window. You can collect more information on debugging and other Xcode features from Xcode 4 user guide. Print Page Previous Next Advertisements ”;
iOS – First iPhone Application ”; Previous Next Creating the First App Now we are going to create a simple single view application (a blank app) that will run on the iOS simulator. The steps are as follows. Step 1 − Open Xcode and select Create a new Xcode project. Step 2 − Select Single View Application. Step 3 − Enter the product name, i.e., the name of the application, organization name, and then the company identifier. Step 4 − Ensure that Use Automatic Reference Counting is selected in order to automatically release the resources allocated once it goes out of scope. Click Next. Step 5 − Select the directory for the project and select create. Step 6 − You will see a screen as follows − In the screen above, you will be able to select the supported orientations, build and release settings. There is a field deployment target, the device version from which we want to support, lets select 4.3, which is the minimum deployment target allowed now. For now, these are not required and let”s focus on running the application. Step 7 − Now, select iPhone simulator in the drop down near Run button and select run. Step 8 − That”s it; you have successfully run your first application. You will get an output as follows − Now let”s change the background color, just to have a start with the interface builder. Select ViewController.xib. Select background option in the right side, change the color and run. In the above project, by default, the deployment target would have been set to iOS 6.0 and auto-layout will be enabled. To ensure that our application runs on devices that are on iOS 4.3 onwards, we have already modified the deployment target at the start of creation of this application, but we didn”t disable auto-layout. To disable auto-layout, we need to deselect the auto-layout checkbox in the file inspector of each nib, i.e., the xib files. The various sections of Xcode project IDE are given in the following figure (Courtesy: Apple Xcode 4 User documentation). File inspector is found in the inspector selector bar as shown above and auto layout can be unchecked there. Auto layout can be used when you want to target only iOS 6 devices. Also, you”ll be able to use many new features like passbook if you raise the deployment target to iOS 6. For now, let”s stick to iOS 4.3 as the deployment target. Code of the First iOS Application You will find five different files that would have been generated for your application. They are listed as follows − AppDelegate.h AppDelegate.m ViewController.h ViewController.m ViewController.xib AppDelegate.h // Header File that provides all UI related items. #import <UIKit/UIKit.h> // Forward declaration (Used when class will be defined /imported in future) @class ViewController; // Interface for Appdelegate @interface AppDelegate : UIResponder <UIApplicationDelegate> // Property window @property (strong, nonatomic) UIWindow *window; // Property Viewcontroller @property (strong, nonatomic) ViewController *viewController; //this marks end of interface @end Important items in code − AppDelegate inherits from UIResponder that handles iOS events. Implements the delegate methods of UIApplicationDelegate, which provides key application events like finished launching, about to terminate and so on. UIWindow object to manage and co-ordinate the various views on the iOS device screen. It”s like the base view over which all other views are loaded. Generally there is only one window for an application. UIViewController to handle the screen flow. AppDelegate.m // Imports the class Appdelegate”s interface import “AppDelegate.h” // Imports the viewcontroller to be loaded #import “ViewController.h” // Class definition starts here @implementation AppDelegate // Method to intimate us that the application launched successfully – (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.viewController = [[ViewController alloc] initWithNibName:@”ViewController” bundle:nil]; self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES; } – (void)applicationWillResignActive:(UIApplication *)application { /* Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.*/ } – (void)applicationWillEnterForeground:(UIApplication *)application { /* Called as part of the transition from the background to the inactive state. Here you can undo many of the changes made on entering the background.*/ } – (void)applicationDidBecomeActive:(UIApplication *)application { /* Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.*/ } – (void)applicationWillTerminate:(UIApplication *)application { /* Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. */ } – (void)applicationWillTerminate:(UIApplication *)application { /* Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. */ } @end Important items in code − UIApplication delegates are defined here. All the methods defined above are UI application delegates and contains no user defined methods. UIWindow object is allocated to hold the application allocated. UIViewController is allocated as the window”s initial view controller. To make the window visible, makeKeyAndVisible method is called. ViewController.h #import <UIKit/UIKit.h> // Interface for class ViewController @interface ViewController : UIViewController @end Important items in code − The ViewController class inherits the UIViewController, which provides the fundamental view management model for the iOS applications. ViewController.m #import “ViewController.h” // Category, an extension of ViewController class @interface ViewController () @end @implementation ViewController – (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } – (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end Important items in code − Two methods implemented here are defined in the base class UIViewController. Do initial setup in viewDidLoad which is called after the view loads. didReceiveMemoryWarning method is called in case of memory warning. Print Page Previous Next
iOS – Audio & Video
iOS – Audio and Video ”; Previous Next Audio and video is quite common in the latest devices. It is supported in iOS with the help of AVFoundation.framework and MediaPlayer.framework respectively. Steps Involved Step 1 − Create a simple View based application. Step 2 − Select your project file, select targets, and then we should add AVFoundation.framework and MediaPlayer.framework. Step 3 − Add two buttons in ViewController.xib and create an action for playing audio and video respectively. Step 4 − Update ViewController.h as follows − #import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> #import <MediaPlayer/MediaPlayer.h> @interface ViewController : UIViewController { AVAudioPlayer *audioPlayer; MPMoviePlayerViewController *moviePlayer; } -(IBAction)playAudio:(id)sender; -(IBAction)playVideo:(id)sender; @end Step 5 − Update ViewController.m as follows − #import “ViewController.h” @interface ViewController () @end @implementation ViewController – (void)viewDidLoad { [super viewDidLoad]; } – (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(IBAction)playAudio:(id)sender { NSString *path = [[NSBundle mainBundle] pathForResource:@”audioTest” ofType:@”mp3″]; audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL: [NSURL fileURLWithPath:path] error:NULL]; [audioPlayer play]; } -(IBAction)playVideo:(id)sender { NSString *path = [[NSBundle mainBundle]pathForResource: @”videoTest” ofType:@”mov”]; moviePlayer = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL fileURLWithPath:path]]; [self presentModalViewController:moviePlayer animated:NO]; } @end Note We need to add audio and video files for ensuring that we get the expected output. Output When we run the application, we”ll get the following output − When we click on play video, we will get an output as shown below − When we click play audio, you will hear the audio. Print Page Previous Next Advertisements ”;
iOS – Discussion
Discuss iOS ”; Previous Next iOS is a mobile operating system developed and distributed by Apple Inc. It was originally released in 2007 for the iPhone, iPod Touch, and Apple TV. iOS is derived from OS X, with which it shares the Darwin foundation. iOS is Apple”s mobile version of the OS X operating system used in Apple computers. Print Page Previous Next Advertisements ”;
iOS – Quick Guide
iOS – Quick Guide ”; Previous Next iOS – Getting Started General Overview iOS, which was previously called iPhone OS, is a mobile operating system developed by Apple Inc. Its first release was in 2007, which included iPhone and iPod Touch. iPad (1st Generation) was released in April 2010 and iPad Mini was released in November 2012. The iOS devices get evolved quite frequently and from experience, we find that at least one version of iPhone and iPad is launched every year. Now, we have iphone5 launched which has its predecessors starting from iPhone, iPhone 3gs, iPhone 4, iPhone 4s. Similarly, iPad has evolved from iPad (1st Generation) to iPad (4th Generation) and an additional iPad Mini version. The iOS SDK has evolved from 1.0 to 6.0. iOS 6.0, the latest SDK is the only officially supported version in Xcode 4.5 and higher. We have a rich Apple documentation and we can find which methods and libraries can be used based on our deployment target. In the current version of Xcode, we’ll be able to choose between deployment targets of iOS 4.3, 5.0 and 6.0. The power of iOS can be felt with some of the following features provided as a part of the device. Maps Siri Facebook and Twitter Multi-Touch Accelerometer GPS High end processor Camera Safari Powerful APIs Game center In-App Purchase Reminders Wide Range of gestures The number of users using iPhone/iPad has increased a great deal. This creates the opportunity for developers to make money by creating applications for iPhone and iPad the Apple”s App Store. For some one new to iOS, Apple has designed an application store where the user can buy apps developed for their iOS devices. A developer can create both free and paid apps to App Store. To develop applications and distribute to the store, the developer will require to register with iOS developer program which costs $99 a year and a Mac with Mountain Lion or higher for its development with latest Xcode. Registering as an Apple Developer An Apple ID is most necessary if you are having any Apple device and being a developer, you definitely need it. It”s free and hence, no issues in having one. The benefits of having an Apple account are as follows − Access to development tools. Worldwide Developers Conference (WWDC) videos. Can join iOS developer program teams when invited. To register an Apple account, follow the steps given below − Step 1 − Click the link https://developer.apple.com/programs/register/ and select “Create Apple ID” Step 2 − Provide the necessary information, which is self explanatory as given in the page. Step 3 − Verify your account with your email verification and the account becomes active. Step 4 − Now you will be able to download the developer tools like Xcode, which is packaged with iOS simulator and iOS SDK, and other developer resources. Apple iOS Developer Program The first question that would arise to a new developer is – Why should I register for an iOS developer program? The answer is quite simple; Apple always focuses on providing quality applications to its user. If there was no registration fee, there could be a possibility of junk apps being uploaded that could cause problems for the app review team of Apple. The benefits of joining the iOS developer program are as follows − Run the apps you develop on the real iOS device. Distribute the apps to the app store. Get access to the developer previews. The steps to join the iOS developer program are as follows − Step 1 − To register, click on the link − (https://developer.apple.com/programs/ios/). Step 2 − Click on Enroll Now in the page that is displayed. Step 3 − You can either sign in to your existing apple account (if you have one) or create a new Apple ID. Step 4 − Thereafter, you have to select between Individual and Company accounts. Use company account if there will be more than one developer in your team. In individual account, you can”t add members. Step 5 − After entering the personal information (for those who newly registers), you can purchase and activate the program by paying with the help of your credit card (only accepted mode of payment). Step 6 − Now you will get access to developer resources by selecting the member center option in the page. Step 7 − Here you will be able to do the following − Create provisioning profiles. Manage your team and devices. Managing application to app store through iTunes Connect. Get forum and technical support. iOS – Environment Setup iOS – Xcode Installation Step 1 − Download the latest version of Xcode from https://developer.apple.com/downloads/ Step 2 − Double click the Xcode dmg file. Step 3 − You will find a device mounted and opened. Step 4 − There will be two items in the window that”s displayed namely, Xcode application and the Application folder”s shortcut. Step 5 − Drag the Xcode to application and it will be copied to your applications. Step 6 − Now Xcode will be available as a part of other applications from which you can select and run. You also have another option of downloading Xcode from the Mac App store and then install following the step-by-step procedure given on the screen. Interface Builder Interface builder is the tool that enables easy creation of UI interface. You have a rich set of UI elements that is developed for use. You just have to drag and drop into your UI view. We”ll learn about adding UI elements, creating outlets and actions for the UI elements in the upcoming pages. You have objects library at the right bottom that consists the entire necessary UI element. The user interface is often referred as xibs, which is its file extension. Each of the xibs is linked to a corresponding view controller. iOS Simulator An iOS simulator actually consists of two types of devices, namely iPhone and iPad with their different versions.
iOS – In-App Purchase
iOS – In-App Purchase ”; Previous Next In-App purchase is used to purchase additional content or upgrade features with respect to an application. Steps Involved Step 1 − In iTunes connect, ensure that you have a unique App ID and when we create the application update with the bundle ID and code signing in Xcode with corresponding provisioning profile. Step 2 − Create a new application and update application information. You can know more about this in apple”s Add new apps documentation. Step 3 − Add a new product for in-app purchase in Manage In-App Purchase of your application”s page. Step 4 − Ensure you setup the bank details for your application. This needs to be setup for In-App purchase to work. Also, create a test user account using Manage Users option in iTunes connect page of your app. Step 5 − The next steps are related to handling code and creating UI for our In-App purchase. Step 6 − Create a single view application and enter the bundle identifier is the identifier specified in iTunes connect. Step 7 − Update the ViewController.xib as shown below − Step 8 − Create IBOutlets for the three labels and the button naming them as productTitleLabel, productDescriptionLabel, productPriceLabel and purchaseButton respectively. Step 9 − Select your project file, then select targets and then add StoreKit.framework. Step 10 − Update ViewController.h as follows − #import <UIKit/UIKit.h> #import <StoreKit/StoreKit.h> @interface ViewController : UIViewController< SKProductsRequestDelegate,SKPaymentTransactionObserver> { SKProductsRequest *productsRequest; NSArray *validProducts; UIActivityIndicatorView *activityIndicatorView; IBOutlet UILabel *productTitleLabel; IBOutlet UILabel *productDescriptionLabel; IBOutlet UILabel *productPriceLabel; IBOutlet UIButton *purchaseButton; } – (void)fetchAvailableProducts; – (BOOL)canMakePurchases; – (void)purchaseMyProduct:(SKProduct*)product; – (IBAction)purchase:(id)sender; @end Step 11 − Update ViewController.m as follows − #import “ViewController.h” #define kTutorialPointProductID @”com.tutorialPoints.testApp.testProduct” @interface ViewController () @end @implementation ViewController – (void)viewDidLoad { [super viewDidLoad]; // Adding activity indicator activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; activityIndicatorView.center = self.view.center; [activityIndicatorView hidesWhenStopped]; [self.view addSubview:activityIndicatorView]; [activityIndicatorView startAnimating]; //Hide purchase button initially purchaseButton.hidden = YES; [self fetchAvailableProducts]; } – (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)fetchAvailableProducts { NSSet *productIdentifiers = [NSSet setWithObjects:kTutorialPointProductID,nil]; productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers]; productsRequest.delegate = self; [productsRequest start]; } – (BOOL)canMakePurchases { return [SKPaymentQueue canMakePayments]; } – (void)purchaseMyProduct:(SKProduct*)product { if ([self canMakePurchases]) { SKPayment *payment = [SKPayment paymentWithProduct:product]; [[SKPaymentQueue defaultQueue] addTransactionObserver:self]; [[SKPaymentQueue defaultQueue] addPayment:payment]; } else { UIAlertView *alertView = [[UIAlertView alloc]initWithTitle: @”Purchases are disabled in your device” message:nil delegate: self cancelButtonTitle:@”Ok” otherButtonTitles: nil]; [alertView show]; } } -(IBAction)purchase:(id)sender { [self purchaseMyProduct:[validProducts objectAtIndex:0]]; purchaseButton.enabled = NO; } #pragma mark StoreKit Delegate -(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions { for (SKPaymentTransaction *transaction in transactions) { switch (transaction.transactionState) { case SKPaymentTransactionStatePurchasing: NSLog(@”Purchasing”); break; case SKPaymentTransactionStatePurchased: if ([transaction.payment.productIdentifier isEqualToString:kTutorialPointProductID]) { NSLog(@”Purchased “); UIAlertView *alertView = [[UIAlertView alloc]initWithTitle: @”Purchase is completed succesfully” message:nil delegate: self cancelButtonTitle:@”Ok” otherButtonTitles: nil]; [alertView show]; } [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; break; case SKPaymentTransactionStateRestored: NSLog(@”Restored “); [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; break; case SKPaymentTransactionStateFailed: NSLog(@”Purchase failed “); break default: break; } } } -(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response { SKProduct *validProduct = nil; int count = [response.products count]; if (count>0) { validProducts = response.products; validProduct = [response.products objectAtIndex:0]; if ([validProduct.productIdentifier isEqualToString:kTutorialPointProductID]) { [productTitleLabel setText:[NSString stringWithFormat: @”Product Title: %@”,validProduct.localizedTitle]]; [productDescriptionLabel setText:[NSString stringWithFormat: @”Product Desc: %@”,validProduct.localizedDescription]]; [productPriceLabel setText:[NSString stringWithFormat: @”Product Price: %@”,validProduct.price]]; } } else { UIAlertView *tmp = [[UIAlertView alloc] initWithTitle:@”Not Available” message:@”No products to purchase” delegate:self cancelButtonTitle:nil otherButtonTitles:@”Ok”, nil]; [tmp show]; } [activityIndicatorView stopAnimating]; purchaseButton.hidden = NO; } @end Note You have to update kTutorialPointProductID to the productID you have created for your In-App Purchase. You can add more than one product by updating the productIdentifiers”s NSSet in fetchAvailableProducts. Similary, handle the purchase related actions for product IDs you add. Output When we run the application, we”ll get the following output − Ensure you had logged out of your account in the settings screen. On clicking the Initiate Purchase, select Use Existing Apple ID. Enter your valid test account username and password. You will be shown the following alert in a few seconds. Once your product is purchased successfully, you will get the following alert. You can see relevant code for updating the application features where we show this alert. Print Page Previous Next Advertisements ”;