How to get started coding In-App Purchase - iphone

I am working on in-app purchase. In my application we added the following code in appdelegate:
#import "InappPurchaseAppDelegate.h"
#import "MainController.h"
#import "MKStoreManager.h"
#import "MKStoreObserver.h"
#implementation InappPurchaseAppDelegate
#synthesize window;
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
[MKStoreManager sharedManager];
navigationController = [[UINavigationController alloc] init];
[window addSubview:navigationController.view];
MainController *frontController =[[MainController alloc] init];
[navigationController pushViewController:frontController animated:NO ];
[frontController release]; // Override point for customization after application launch
[window makeKeyAndVisible];
}
and added the following code in our controller:
#import "MainController.h"
#import "MKStoreManager.h"
#import "MKStoreObserver.h"
#import "InappPurchaseAppDelegate.h"
#implementation MainController
-(IBAction)InappPurchase:(id)sender
{
[[MKStoreManager sharedManager] buyFeatureA];
}
I also added storekit framework but when the button is clicked nothing happens.

All you need to know is here: http://developer.apple.com/iphone/library/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Overview%20of%20the%20Store%20Kit%20API/OverviewoftheStoreKitAPI.html#//apple_ref/doc/uid/TP40008267-CH100-SW1
It shouldn't take you more than half a day to implement it (maybe a bit more if the content resides on your servers and is not already in the bundle).

The simplest explaination is that your button is not properly configured to send the action message. To test either set a breakpoint for the method or log it like:
-(IBAction)InappPurchase:(id)sender
{
NSLog(#"Buyid method called");
[[MKStoreManager sharedManager] buyFeatureA];
}
If the NSLog or breakpoint are never hit, you need to check the button in Interface Builder and make such it's action is set to the InappPurchase method.
If the InappPurchase method is being called by the button then the problem is in the MKStoreManger object.

Related

iOS : is it possible to open previous viewController after crashing and re-launch app?

How to achieve this stuff below? Please give me some guidance for it. I describe my issue below.
When I tap home button and remove app from tray and while I am opening app I get the login screen. I know how to use NSUserDefaults well.
But my issue is that when I navigate 3rd or 4th viewController and I press Home Button and remove app from tray, Then whenever I open app than I want to open with last open viewController.
Also same when my app is Crashing and I am opening it again then I want to open app with last open viewController state.
So I just want to know that is that possible or not? If yes, then please guide me how to achieve this stuff.
Thank you
Yes, both cases are possible.
On crash, you can use UncaughtExceptionHandler to perform some code. In you app delegate, register you handler like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
// Other didFinishLaunchingWithOptions code
And add your handler method to the same .m file
void uncaughtExceptionHandler(NSException *exception)
{
// App crashed, save last selected tabbar index to the to the NSUserDefaults
[[NSUserDefaults standardUserDefaults] setInteger:tabBarController.selectedIndex forKey:#"LastSelectedTabbarIndex"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
While app runs, to keep track of last selected tab bar controller, use UITabBarControllerDelegate and save newly selected tabbar's index to NSUserDefaults. Short example:
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
NSUInteger tabIndex = [[tabBarController viewControllers] indexOfObject:viewController];
// I have newly selected index, now save it to the NSUserDefaults
}
This code will save last selected tabbar's index to the NSUserDefaults every time tabbar's selected index changes.
Finally, when you app starts (in your didFinishLaunchingWithOptions), read last saved tabbar index from NSUserDefaults and set tabbar's selected index accordingly
self.tabBarController.selectedIndex = lastSelectedIndexFromDefaults;
Edit:
If you also need to restore UINavigationControllers controllers stack, its pretty difficult task. I give you just a quick overview what comes to my mind.
There are 2 cases:
You have custom view controllers initializers and need to pass custom object to those controllers - In this case, its almost impossible (in some reasonable time) implement this
You use only -init or -initWithNibName...: to initialize view controllers in navigation stack. You could enumerate controllers from the root UINavigationController of the tab, get their classes names using NSStringFromClass and save them to NSUserDefaults. On apps start, you would reverse procedure (initialize controllers using their names strings read from NSUserDefaults using something like this: UIViewController *vc = [[NSClassFromString(#"aa") alloc] init];).
I understand you are ok with the code part so i will just give my suggestion
on viewDidLoad of every view controller set a nsuserdefault value of the top most object on navigation array.
if their are not too many branches then you can manage the push at root view controller easily
This is not the proper answer but you can use it for Navigating view after launching.
In AppDelegate file use below codes:---
#import "NewSAppDelegate.h"
#import "NewSViewController.h"
static NewSAppDelegate *globalSelf;
#implementation NewSAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[NewSViewController alloc] initWithNibName:#"NewSViewController" bundle:nil];
self.navController=[[UINavigationController alloc] initWithRootViewController:self.viewController];
self.window.rootViewController = self.navController;
[self.window makeKeyAndVisible];
globalSelf=self;
NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
return YES;
}
void uncaughtExceptionHandler(NSException *exception)
{
UIViewController *currentVC = globalSelf.navController.visibleViewController;
[[NSUserDefaults standardUserDefaults] setObject:NSStringFromClass(currentVC.class) forKey:#"lastVC"];
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIViewController *currentVC = self.navController.visibleViewController;
[[NSUserDefaults standardUserDefaults] setObject:NSStringFromClass(currentVC.class) forKey:#"lastVC"];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"appDidBecomeActive" object:nil];
// 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.
}
In your login viewController's init method add an observer for notification and in notification method , you can apply if conditions for viewController's name received.and push to that viewController on launching LoginView controller as:---
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(openLastVC)
name:#"appDidBecomeActive"
object:nil];
// Custom initialization
}
return self;
}
-(void)openLastVC
{
NSLog(#"val ==%#",[[NSUserDefaults standardUserDefaults] valueForKey:#"lastVC"]);
if ([[[NSUserDefaults standardUserDefaults] valueForKey:#"lastVC"] isEqualToString:#"GhachakViewController"]) {
GhachakViewController *gvc=[[GhachakViewController alloc] initWithNibName:#"GhachakViewController" bundle:nil];
[self.navigationController pushViewController:gvc animated:NO];
}
}
May this help you....

UIActionSheet code crashes when moved from UIViewController file to separate class file

I have searched and searched the board(s) and am not able to figure this out. It has got to be something simple and right in front of me.
I am trying clean up my code and make it more reusable. I was taking some UIActionSheet code that works from a UIViewController and making its own object file. Works fine, until I add UIActionSheetDelegate methods.
When a button is pressed, instead of firing the actionSheetCancel method, it crashes with no stack trace. Every time.
My code is below. Any help would be appreciated. My guess has been it is because I am not using the xcode storyboard tool to connect things together, but I would think this is legal.
egcTestSheet.h:
#import <UIKit/UIKit.h>
#interface egcTestSheet : NSObject <UIActionSheetDelegate> {
}
- (void) showSheet:(UITabBar *) tabBar
displayTitle:(NSString *) name;
#end
egcTestSheet.m
#import "egcTestSheet.h"
#implementation egcTestSheet
-(void) showSheet:(UITabBar *)tabBar displayTitle:(NSString *)name{
UIActionSheet *menu = [[UIActionSheet alloc] initWithTitle:name
delegate:self
cancelButtonTitle:#"Done"
destructiveButtonTitle:#"Cancel"otherButtonTitles:nil];
[menu showFromTabBar:tabBar];
[menu setBounds:CGRectMake(0,0,320, 700)];
}
// actionsheet delegate protocol item
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex: (NSInteger)buttonIndex{
NSLog(#"button index = %d", buttonIndex);
}
- (void)actionSheetCancel:(UIActionSheet *)actionSheet{
NSLog(#"in action canceled method");
}
#end
call code from a UIViewController object:
egcTestSheet *sheet = [[egcTestSheet alloc] init];
[sheet showSheet:self.tabBarController.tabBar displayTitle:#"new test"];
Your action sheet is probably being released as it is dismissed (are you using ARC?). This means when it tries to call it's delegate to inform said delegate of its dismissal/selection, it is trying to call self. Self is a dangling pointer by this time, because it has been released.
In the view controller that is presenting/calling this action sheet, set a property to keep a reference to the action sheet. Set the property to nil on dismissal of the action sheet.

Trying to make my iphone app universal. Navigation Controller keeps saying Unbalanced calls

have been trying couple of hours now to make my iphone app universal. The mission was successful but have a strange problem. The navigation controller keeps pushing things without even pushing anything. The app doesn't crash but it gives me a message in the console
nested push animation can result in corrupted navigation bar
2012-02-06 10:52:07.701 ##$%^^$[54755:207] Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted.
2012-02-06 10:52:07.704 !##$%^$%#[54755:207] Unbalanced calls to begin/end appearance transitions for <searchEditViewController: 0xc652150>.
and here is how i've set app the whole thing :
![navigation screen shot][1]
here is my code in the AppDelegate_iphone.h
#import <UIKit/UIKit.h>
#import "iPhoneView.h"
#import "AboutUsViewController.h"
#import "FavoritesViewController.h"
#class iPhoneView;
#interface AppDelegate_iPhone : NSObject <UIApplicationDelegate> {
UITabBarController *tabBarController;
UINavigationController *homeNavigationController;
UINavigationController *favouritesNavigationController;
AboutUsViewController *aboutUsViewController;
iPhoneView * search;
FavoritesViewController *favoritesViewController;
UIWindow *window;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet iPhoneView *search;
#property (nonatomic, retain) FavoritesViewController *favoritesViewController;
#end
and here is on my AppDelegate.m file
#import "AppDelegate_iPhone.h"
#import "iPhoneView.h"
#implementation AppDelegate_iPhone
#synthesize window,search,favoritesViewController;
#pragma mark -
#pragma mark Application lifecycle
- (void)applicationDidFinishLaunching:(UIApplication *)application
{ tabBarController = [[UITabBarController alloc] init];
homeNavigationController = [[UINavigationController alloc] init];
search = [[iPhoneView alloc] init];
[homeNavigationController pushViewController:search animated:NO];
favouritesNavigationController = [[UINavigationController alloc] init];
favoritesViewController = [[FavoritesViewController alloc]init];
[favouritesNavigationController pushViewController:favoritesViewController animated:NO];
aboutUsViewController =[[AboutUsViewController alloc] init];
UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:#"επικοινωνία" image:[UIImage imageNamed:#"aboutus"] tag:0];
aboutUsViewController.tabBarItem = item;
[item release];
UITabBarItem *item2 = [[UITabBarItem alloc] initWithTitle:#"αγαπημένα" image:[UIImage imageNamed:#"favorites"] tag:0];
favouritesNavigationController.tabBarItem = item2;
[item2 release];
NSArray *tabBarControllerCollection = [NSArray arrayWithObjects:homeNavigationController,favouritesNavigationController,aboutUsViewController,nil];
[tabBarController setViewControllers:tabBarControllerCollection animated:NO];
[window addSubview:tabBarController.view];
[window makeKeyAndVisible];
}
- (void)applicationWillResignActive:(UIApplication *)application {
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
}
- (void)applicationDidEnterBackground:(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, called instead of applicationWillTerminate: when the user quits.
*/
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
/*
Called as part of 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.
See also applicationDidEnterBackground:.
*/
}
#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
/*
Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
*/
}
- (void)dealloc {
[tabBarController release];
[search release];
[favoritesViewController release];
[favouritesNavigationController release];
[aboutUsViewController release];
[window release];
[super dealloc];
}
#end
OK solved had connected the button 2 times with the same action in IB. Took me 48hours to figure it out!

How to remove UINavigationViewController

I have created one navigationController in name_of_my_appAppDelegate.h...
After the use I want to remove it from the superview...
in my name_of_my_RootViewController I want to call it and remove.
How to call it?
In the NewsPadViewController, how to remove the NavigationController when I finished to use it?
#import <UIKit/UIKit.h>
#class NewsPadViewController;
#interface NewsPadAppDelegate : NSObject <UIApplicationDelegate>{
UIWindow *window;
UINavigationController *navigationController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
#end
and this is the implementation
#import "NewsPadAppDelegate.h"
#import "NewsPadViewController.h"
#implementation NewsPadAppDelegate
#synthesize window;
#synthesize navigationController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[window addSubview:navigationController.view];
[window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
}
- (void)applicationDidEnterBackground:(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 active 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)dealloc
{
[navigationController release];
[window release];
[super dealloc];
}
#end
Check this out: UINavigationController Class Reference.
You probably want something like this:
[name_of_my_RootViewController popToRootViewControllerAnimated:YES];
Or:
[name_of_my_RootViewController.view removeFromSuperview];
Or:
for (UIView *v in self.view.subviews) {
if ([v isEqual:myView]) {
[myView removeFromSuperview];
}
}
Or:
[((NewsPadAppDelegate *)[[UIApplication sharedApplication] delegate]).window.rootViewController.view removeFromSuperview];
To remove the view controller you remove its view, like this:
[name_of_my_RootViewController.view removeFromSuperview];
Sounds like you should be presenting the UINavigationController modally in the first place. Set up a plain UIViewController called rootViewController and make that visible instead of the navigation controller, then call:
[rootViewController presentModalViewController:navigationController animated:YES];
And when you're done with it, hit a button on the navigation controller which calls:
[self dismissModalViewControllerAnimated:YES];
And you'll go back to the plain UIViewController where you can show the rest of your app.

Crash in ABPeoplePicker when called from another modal viewcontroller and both dismissed

(Note: I filed this question before in the context of my project, but I've now recreated the crash in a test project. Any help in telling me what I'm doing wrong would be appreciated.)
The crash occurs when calling ABPeoplePicker from another modal viewcontroller. Specifically, the main window has a NavController, which loads myVC. myVC then loads a modal NavController containing my controller, which then calls ABPeoplePicker. In this demo program, no user intervention is necessary until ABPeoplePicker runs.
The crash occurs if you use the search box in the people picker, and then select one of the resulting people. (If you use the simulator, you'll need to add a person in Contacts before running the program.) The program returns, but during the dismissal of the two modal VCs, I get an assertion error crash. It occurs every time on iphone, ipad, and simulators for both. This seems a very normal thing to do, so I find it hard to believe this is a real bug. The crash message is:
Assertion failure in
-[ABMembersSearchDisplayController setActive:animated:],
/SourceCache/UIKit_Sim/UIKit-1448.69/UISearchDisplayController.m:589 2011-01-31 13:51:11.903
testcrasher2[26044:207] *
Terminating app due to uncaught
exception
'NSInternalInconsistencyException',
reason: 'search contents navigation
controller must not change between
-setActive:YES and -setActive:NO'
So to demonstrate, in a new Xcode iPhone Window application, I modify the didFinishLaunchingWithOptions to call my controller. Then I create two VCs as follows. (Note you need to add Addressbook frameworks to the target.) Here's the entire program...
AppDelegate.didFinishLaunchingWithOptions:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
myViewController *detailViewController = [[myViewController alloc] init];
// Set the navigation controller as the window's root view controller and display.
UINavigationController * navController = [[UINavigationController alloc] initWithRootViewController: detailViewController];
self.window.rootViewController = navController;
[self.window makeKeyAndVisible];
[detailViewController release];
[navController release];
return YES;
}
myViewController.h:
#interface myViewController : UIViewController<addDelegate>{
}
#end
myViewController.m:
#import "myViewController.h"
#import "AddNewViewController.h"
#implementation myViewController
- (void)controllerDidFinish:(addNewViewController *)controller {
[self dismissModalViewControllerAnimated:YES];
}
-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear: animated];
addNewViewController *addController = [[addNewViewController alloc] init];
addController.delegate = self;
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:addController];
[self presentModalViewController:navController animated:YES];
[navController release];
[addController release];
}
#end
AddNewViewController.h:
#import <AddressBookUI/AddressBookUI.h>
#protocol addDelegate;
#interface addNewViewController : UIViewController < ABPeoplePickerNavigationControllerDelegate> {
id <addDelegate> delegate;
}
#property(nonatomic, assign) id <addDelegate> delegate;
#end
#protocol addDelegate <NSObject>
- (void)controllerDidFinish:(addNewViewController *)controller ;
#end
AddNewViewController.m:
#import "AddNewViewController.h"
#implementation addNewViewController
#synthesize delegate;
-(void) viewDidAppear:(BOOL)animated {
ABPeoplePickerNavigationController * peoplepicker = [[ABPeoplePickerNavigationController alloc] init] ;
peoplepicker.peoplePickerDelegate = self;
[self presentModalViewController:peoplepicker animated:YES];
[peoplepicker release];
}
#pragma mark AddressBook delegate methods
- (void)peoplePickerNavigationControllerDidCancel: (ABPeoplePickerNavigationController *)peoplePicker {
[self dismissModalViewControllerAnimated:YES];
}
- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker
shouldContinueAfterSelectingPerson:(ABRecordRef)person {
[self.delegate controllerDidFinish:self ];
return NO; //EDIT: This MUST be YES or it will crash (see answer below)
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker
shouldContinueAfterSelectingPerson:(ABRecordRef)person
property:(ABPropertyID)property
identifier:(ABMultiValueIdentifier)identifier {
return NO;
}
#end
Turns out this is an actual bug. It is indeed true that if you do a double ModalVC dismiss to ABPeoplePicker when the user clicks a person in search, you'll get this crash. Fortunately, there's a simple workaround: return YES in your delegate's shouldContinueAfterSelectingPerson. As you're simultaneously dismissing the picker, it doesn't really matter whether you return YES or NO, it won't continue, but NO will crash and YES doesn't. (Same answer as for my original post: Weird crash in ABPeoplePicker )
The bug is in fact in your code. Took me a few minutes to find it, I'll try to explain as best I can.
Your
ABPeoplePickerNavigationController
is currently presented modally.
You click in the search bar and type
some stuff.
You click a person's name.
What happens here, is the ABPeoplePickerNavigationController asks its delegate (which is your addNewViewController) whether it should continue after selecting a person. While it's waiting to hear back from you, you suddenly call your own protocol's method (in myViewController) that attempts to dismiss the modal addNewViewController. You're jumping ahead of yourself, as the ABPeoplePickerNavigationController is still open.
Change your implementation of the ABPeoplePickerNavigationControllerDelegate method to read:
- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker
shouldContinueAfterSelectingPerson:(ABRecordRef)person {
// This line is new.
[self.navigationController dismissModalViewControllerAnimated:YES];
[self.delegate controllerDidFinish:self];
return NO;
}
And your crash will go away. When you're dealing with layers upon layers of UIViewControllers and UINavigationControllers, you have to be very careful to dismiss them in the reverse order you presented them.