Redirect UIAlertView Button Push Notifications - iphone

I have read many posts on this matter, but none of them really helps me out. It seems quite easy to do, but somehow I can't figure it out.
What am I trying to do here?
Well, I send a push notifications to my app. Everything works fine.
I can handle it when it is in the background, inactive or even when the app is not running.
But one other state - app in foreground - gives me a headache.
I have this code snippet which I'm using. All fine.
When the app is running in the foreground, the user gets the UIAlertview.
But how do I add an action to the view button?
This particular action I mean: when someone taps the view button he/she gets redirected to the url which has been passed through the push notification.
Just like I have used before in the code snippet (this part to be precise):
NSString *notifUrl = [apsInfo objectForKey:#"url"];
NSLog(#"Received Push Url: %#", notifUrl);
I hope this makes sense and someone can help me out. I'm lost at this one ... This is the entire code snippet which is relevant at this subject.
-(void)Redirect:(NSString*)url{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
NSLog(#"%#",url);
}
/**
* Remote Notification Received while application was open.
*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
#if !TARGET_IPHONE_SIMULATOR
NSLog(#"remote notification: %#",[userInfo description]);
NSDictionary *apsInfo = [userInfo objectForKey:#"aps"];
NSString *alert = [apsInfo objectForKey:#"alert"];
NSLog(#"Received Push Alert: %#", alert);
NSString *sound = [apsInfo objectForKey:#"sound"];
NSLog(#"Received Push Sound: %#", sound);
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
NSString *badge = [apsInfo objectForKey:#"badge"];
NSLog(#"Received Push Badge: %#", badge);
application.applicationIconBadgeNumber = [[apsInfo objectForKey:#"badge"] integerValue];
NSString *notifUrl = [apsInfo objectForKey:#"url"];
NSLog(#"Received Push Url: %#", notifUrl);
// app was already in the foreground
if ( application.applicationState == UIApplicationStateActive ) {
UIAlertView *alertPush = [[UIAlertView alloc]initWithTitle: #"Message"
message: alert
delegate: self
cancelButtonTitle:#"View"
otherButtonTitles: #"Cancel", nil];
[alertPush show];
[alertPush release];
}
// app is inactive or in the background
else {
[self Redirect:notifUrl];
}
#endif
}
// what to do if user taps the viewbutton in push notification alert view
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == 0) {
NSLog(#"View Button has been tapped");
// We need the url that has been passed by the push notification
}
else {
// Do something
}
}

Just define your variable notifUrl in .h file so that you can access this in other methods of your class as well. Then store url in that variable and use that in alertview delegate method.
//Add this in .h file
NSString *notifUrl;
//Add this in .m file
-(void)Redirect:(NSString*)url{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
NSLog(#"%#",url);
}
/**
* Remote Notification Received while application was open.
*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
#if !TARGET_IPHONE_SIMULATOR
NSLog(#"remote notification: %#",[userInfo description]);
NSDictionary *apsInfo = [userInfo objectForKey:#"aps"];
NSString *alert = [apsInfo objectForKey:#"alert"];
NSLog(#"Received Push Alert: %#", alert);
NSString *sound = [apsInfo objectForKey:#"sound"];
NSLog(#"Received Push Sound: %#", sound);
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
NSString *badge = [apsInfo objectForKey:#"badge"];
NSLog(#"Received Push Badge: %#", badge);
application.applicationIconBadgeNumber = [[apsInfo objectForKey:#"badge"] integerValue];
//Define this variable in .h file so that you can access this in other methods as well
notifUrl = [apsInfo objectForKey:#"url"];
NSLog(#"Received Push Url: %#", notifUrl);
[notifUrl retain]; // this is retain value of notifUrl so that you can use it later
// app was already in the foreground
if ( application.applicationState == UIApplicationStateActive ) {
UIAlertView *alertPush = [[UIAlertView alloc]initWithTitle: #"Message"
message: alert
delegate: self
cancelButtonTitle:#"View"
otherButtonTitles: #"Cancel", nil];
[alertPush show];
[alertPush release];
}
// app is inactive or in the background
else {
[self Redirect:notifUrl];
}
#endif
}
// what to do if user taps the viewbutton in push notification alert view
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == 0) {
NSLog(#"View Button has been tapped");
NSLog(#"Received Push Url: %#", notifUrl);
[self Redirect:notifUrl];
}
else {
// Do something
}
}

Related

UIAlertView doesn't work

I have an alert view with the two buttons, but the buttons don't open the urls. I don't know the error. Help please.
Here's the code:
-(IBAction)showAlertView {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Obrir en..."
message:#"Es pot requirir la aplicació de Google Maps"
delegate:self
cancelButtonTitle:#"Millor no..."
otherButtonTitles:#"Mapes",#"Google Maps",nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Mapes"])
{
UIApplication *ourApplication = [UIApplication sharedApplication];
NSString *ourPath = #"http://maps.apple.com/?q=Plaça+del+Rei+43003+Tarragona";
NSURL *ourURL = [NSURL URLWithString:ourPath];
[ourApplication openURL:ourURL];
}
if([title isEqualToString:#"Google Maps"])
{
UIApplication *ourApplication = [UIApplication sharedApplication];
NSString *ourPath = #"comgooglemaps://?daddr=Plaça+del+Rei+43003+Tarragona&directionsmode=walking";
NSURL *ourURL = [NSURL URLWithString:ourPath];
[ourApplication openURL:ourURL];
}
}
I think the special character (ç) in the address is throwing the NSURL off. Try using the stringByAddingPercentEscapesUsingEncoding: method of NSString to encode it before passing it to the NSURL initializer.
Please check the URL which we fired.
if([ourApplication canOpenURL:ourURL])
[ourApplication openURL:ourURL];
else
NSLog(#"URL is not valid.");
As I check with both URL, they are not able to open.
You can check the URL with above code whether URL is able to open or not.
You have to check the URL's, try this:
-(IBAction)showAlertView {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Obrir en..."
message:#"Es pot requirir la aplicació de Google Maps"
delegate:self
cancelButtonTitle:#"Millor no..."
otherButtonTitles:#"Mapes",#"Google Maps",nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//0 is cancel
if(buttonIndex == 1)
{
[self openURLWithString:#"https://www.google.com/maps/preview#!q=Pla%C3%A7a+del+Rei+43003+Tarragona&data=!1m4!1m3!1d4618!2d1.2582895!3d41.1168719!4m11!1m10!4m8!1m3!1d26081603!2d-95.677068!3d37.0625!3m2!1i1024!2i768!4f13.1!17b1"];
}
if(buttonIndex == 2)
{
[self openURLWithString:#"https://www.google.com/maps/preview#!data=!1m4!1m3!1d18473!2d1.258181!3d41.1168316!4m13!3m12!1m0!1m1!1sPla%C3%A7a+del+Rei+43003+Tarragona!3m8!1m3!1d26081603!2d-95.677068!3d37.0625!3m2!1i1024!2i768!4f13.1&fid=0"];
}
}
- (void)openURLWithString:(NSString *)string{
UIApplication *ourApplication = [UIApplication sharedApplication];
NSString *ourPath = string;
NSURL *ourURL = [NSURL URLWithString:ourPath];
if([ourApplication canOpenURL:ourURL])
[ourApplication openURL:ourURL];
else
NSLog(#"URL is not valid.");
}
First, you should use elseif in your second condition, because you only want to fire the second if the first isn't true. Second, it seems to be the URL you're using in #"Mapes"... I tested this and that URL seems to be the culprit. When I changed that URL to another test URL, it worked.

Advertisements not removed after IAP unless app is restarted?

In my app, there is code that, if a button is pressed the user can upgrade the app and remove the advertisements, it calls the MKStoreKit and once the user purchases the upgrade, the adverts do remain in the app UNTIL the app is restarted.
I want to fix this, so the advertisements are removed immediately, but how would I go about doing this?
Here is some of the code;
-(IBAction)removeAds:(id)sender
{
if (![MKStoreManager isFeaturePurchased:#"com.davidsapps.puzzler.removeads"]) { //
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Upgrade App" message:#"To upgrade and remove all advertisements from this app Please click OK to purchase the upgrade!" delegate:self cancelButtonTitle:#"No Thanks" otherButtonTitles:#"Yes Please",nil];
[alert show];
[alert release];
}
}
The alert it links to;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0){
//cancel button clicked. Do something here or nothing here
}
else{
//other button indexes clicked
[[MKStoreManager sharedManager] buyFeature:#- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0){
//cancel button clicked. Do something here or nothing here
}
else{
//other button indexes clicked
[[MKStoreManager sharedManager] buyFeature:#"com.idevver.mybatterypal.upgrade"];
}
}
}
Using MKStoreKit
Is there anything I can do to make it remove the advertisements without the user having to restart the app?
Thanks,
Chris
EDIT - the advertisements are Admob Mediation, using this code in the ViewDidLoad
- (void)viewDidLoad {
bannerView_ = [[GADBannerView alloc] initWithAdSize:kGADAdSizeSmartBannerPortrait];
bannerView_.adUnitID = MY_BANNER_UNIT_ID;
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
CGFloat screenXPos = (screenWidth /2);
CGFloat screenYPos = screenHeight - 90;
[bannerView_ setCenter:CGPointMake(screenXPos, screenYPos)];
bannerView_.rootViewController = self;
bannerView_.adUnitID = MY_BANNER_UNIT_ID;
bannerView_.rootViewController = self;
[self.view addSubview:bannerView_];
This is the code that actually calls the advertisement banner, it is in an if/else statement later in the viewDidLoad
if (![MKStoreManager isFeaturePurchased:#"com.davidsapps.puzzler.removeads"]) { //
[bannerView_ loadRequest:[GADRequest request]];
}
So I guess somehow when the feature is purchased, I need to add to the MKStoreManager.m file something to say dismiss the bannerView_ code above?
Would that work?
EDIT 2 - Full .m file for the in-app code (with thanks to MugunthKumar for a wonderful kit)
//
// MKStoreManager.m
// MKStoreKit
//
// Created by Mugunth Kumar on 17-Nov-2010.
// Copyright 2010 Steinlogic. All rights reserved.
// File created using Singleton XCode Template by Mugunth Kumar (http://mugunthkumar.com
// Permission granted to do anything, commercial/non-commercial with this file apart from removing the line/URL above
// Read my blog post at http://mk.sg/1m on how to use this code
// As a side note on using this code, you might consider giving some credit to me by
// 1) linking my website from your app's website
// 2) or crediting me inside the app's credits page
// 3) or a tweet mentioning #mugunthkumar
// 4) A paypal donation to mugunth.kumar#gmail.com
//
// A note on redistribution
// While I'm ok with modifications to this source code,
// if you are re-publishing after editing, please retain the above copyright notices
#import "MKStoreManager.h"
#import "GADBannerView.h"
#import "AppDelegate.h"
#interface MKStoreManager (PrivateMethods)
- (void) requestProductData;
- (BOOL) canCurrentDeviceUseFeature: (NSString*) featureID;
- (BOOL) verifyReceipt:(NSData*) receiptData;
- (void) enableContentForThisSession: (NSString*) productIdentifier;
#end
#implementation MKStoreManager
#synthesize purchasableObjects = _purchasableObjects;
#synthesize storeObserver = _storeObserver;
static NSString *ownServer = nil;
static __weak id<MKStoreKitDelegate> _delegate;
static MKStoreManager* _sharedStoreManager;
- (void)dealloc {
[_purchasableObjects release];
[_storeObserver release];
[_sharedStoreManager release];
[super dealloc];
}
#pragma mark Delegates
+ (id)delegate {
return _delegate;
}
+ (void)setDelegate:(id)newDelegate {
_delegate = newDelegate;
}
#pragma mark Singleton Methods
+ (MKStoreManager*)sharedManager
{
#synchronized(self) {
if (_sharedStoreManager == nil) {
#if TARGET_IPHONE_SIMULATOR
NSLog(#"You are running in Simulator MKStoreKit runs only on devices");
#else
_sharedStoreManager = [[self alloc] init];
_sharedStoreManager.purchasableObjects = [[NSMutableArray alloc] init];
[_sharedStoreManager requestProductData];
_sharedStoreManager.storeObserver = [[MKStoreObserver alloc] init];
[[SKPaymentQueue defaultQueue] addTransactionObserver:_sharedStoreManager.storeObserver];
#endif
}
}
return _sharedStoreManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
#synchronized(self) {
if (_sharedStoreManager == nil) {
_sharedStoreManager = [super allocWithZone:zone];
return _sharedStoreManager; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
#pragma mark Internal MKStoreKit functions
- (void) restorePreviousTransactions
{
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
-(void) requestProductData
{
SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObjects:
kFeatureAId,
kConsumableFeatureBId,
kConsumableBaseFeatureId,
nil]];
request.delegate = self;
[request start];
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
[self.purchasableObjects addObjectsFromArray:response.products];
#ifndef NDEBUG
for(int i=0;i<[self.purchasableObjects count];i++)
{
SKProduct *product = [self.purchasableObjects objectAtIndex:i];
NSLog(#"Feature: %#, Cost: %f, ID: %#",[product localizedTitle],
[[product price] doubleValue], [product productIdentifier]);
}
for(NSString *invalidProduct in response.invalidProductIdentifiers)
NSLog(#"Problem in iTunes connect configuration for product: %#", invalidProduct);
#endif
[request autorelease];
isProductsAvailable = YES;
if([_delegate respondsToSelector:#selector(productFetchComplete)])
[_delegate productFetchComplete];
}
// call this function to check if the user has already purchased your feature
+ (BOOL) isFeaturePurchased:(NSString*) featureId
{
return [[NSUserDefaults standardUserDefaults] boolForKey:featureId];
}
// Call this function to populate your UI
// this function automatically formats the currency based on the user's locale
- (NSMutableArray*) purchasableObjectsDescription
{
NSMutableArray *productDescriptions = [[NSMutableArray alloc] initWithCapacity:[self.purchasableObjects count]];
for(int i=0;i<[self.purchasableObjects count];i++)
{
SKProduct *product = [self.purchasableObjects objectAtIndex:i];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setLocale:product.priceLocale];
NSString *formattedString = [numberFormatter stringFromNumber:product.price];
[numberFormatter release];
// you might probably need to change this line to suit your UI needs
NSString *description = [NSString stringWithFormat:#"%# (%#)",[product localizedTitle], formattedString];
#ifndef NDEBUG
NSLog(#"Product %d - %#", i, description);
#endif
[productDescriptions addObject: description];
}
[productDescriptions autorelease];
return productDescriptions;
}
- (void) buyFeature:(NSString*) featureId
{
if([self canCurrentDeviceUseFeature: featureId])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Review request approved", #"")
message:NSLocalizedString(#"You can use this feature for reviewing the app.", #"")
delegate:self
cancelButtonTitle:NSLocalizedString(#"Dismiss", #"")
otherButtonTitles:nil];
[alert show];
[alert release];
[self enableContentForThisSession:featureId];
return;
}
if ([SKPaymentQueue canMakePayments])
{
SKPayment *payment = [SKPayment paymentWithProductIdentifier:featureId];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"In-App Purchasing disabled", #"")
message:NSLocalizedString(#"Check your parental control settings and try again later", #"")
delegate:self
cancelButtonTitle:NSLocalizedString(#"Dismiss", #"")
otherButtonTitles: nil];
[alert show];
[alert release];
}
}
- (BOOL) canConsumeProduct:(NSString*) productIdentifier
{
int count = [[NSUserDefaults standardUserDefaults] integerForKey:productIdentifier];
return (count > 0);
}
- (BOOL) canConsumeProduct:(NSString*) productIdentifier quantity:(int) quantity
{
int count = [[NSUserDefaults standardUserDefaults] integerForKey:productIdentifier];
return (count >= quantity);
}
- (BOOL) consumeProduct:(NSString*) productIdentifier quantity:(int) quantity
{
int count = [[NSUserDefaults standardUserDefaults] integerForKey:productIdentifier];
if(count < quantity)
{
return NO;
}
else
{
count -= quantity;
[[NSUserDefaults standardUserDefaults] setInteger:count forKey:productIdentifier];
return YES;
}
}
-(void) enableContentForThisSession: (NSString*) productIdentifier
{
if([_delegate respondsToSelector:#selector(productPurchased:)])
[_delegate productPurchased:productIdentifier];
}
#pragma mark In-App purchases callbacks
// In most cases you don't have to touch these methods
-(void) provideContent: (NSString*) productIdentifier
forReceipt:(NSData*) receiptData
{
if(ownServer != nil && SERVER_PRODUCT_MODEL)
{
// ping server and get response before serializing the product
// this is a blocking call to post receipt data to your server
// it should normally take a couple of seconds on a good 3G connection
if(![self verifyReceipt:receiptData]) return;
}
NSRange range = [productIdentifier rangeOfString:kConsumableBaseFeatureId];
NSString *countText = [productIdentifier substringFromIndex:range.location+[kConsumableBaseFeatureId length]];
int quantityPurchased = [countText intValue];
if(quantityPurchased != 0)
{
int oldCount = [[NSUserDefaults standardUserDefaults] integerForKey:productIdentifier];
oldCount += quantityPurchased;
[[NSUserDefaults standardUserDefaults] setInteger:oldCount forKey:productIdentifier];
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:productIdentifier];
}
[[NSUserDefaults standardUserDefaults] synchronize];
if([_delegate respondsToSelector:#selector(productPurchased:)])
[_delegate productPurchased:productIdentifier];
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"In-App Upgrade" message:#"Successfull removal of advertisements upgrade - thankyou" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
- (void) transactionCanceled: (SKPaymentTransaction *)transaction
{
#ifndef NDEBUG
NSLog(#"User cancelled transaction: %#", [transaction description]);
#endif
if([_delegate respondsToSelector:#selector(transactionCanceled)])
[_delegate transactionCanceled];
}
- (void) failedTransaction: (SKPaymentTransaction *)transaction
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[transaction.error localizedFailureReason]
message:[transaction.error localizedRecoverySuggestion]
delegate:self
cancelButtonTitle:NSLocalizedString(#"Dismiss", #"")
otherButtonTitles: nil];
[alert show];
[alert release];
}
#pragma mark In-App purchases promo codes support
// This function is only used if you want to enable in-app purchases for free for reviewers
// Read my blog post http://mk.sg/31
- (BOOL) canCurrentDeviceUseFeature: (NSString*) featureID
{
NSString *uniqueID = [[UIDevice currentDevice] uniqueIdentifier];
// check udid and featureid with developer's server
if(ownServer == nil) return NO; // sanity check
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", ownServer, #"featureCheck.php"]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *postData = [NSString stringWithFormat:#"productid=%#&udid=%#", featureID, uniqueID];
NSString *length = [NSString stringWithFormat:#"%d", [postData length]];
[theRequest setValue:length forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[[NSError alloc] init] autorelease];
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest
returningResponse:&urlResponse
error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
BOOL retVal = NO;
if([responseString isEqualToString:#"YES"])
{
retVal = YES;
}
[responseString release];
return retVal;
}
// This function is only used if you want to enable in-app purchases for free for reviewers
// Read my blog post http://mk.sg/
-(BOOL) verifyReceipt:(NSData*) receiptData
{
if(ownServer == nil) return NO; // sanity check
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", ownServer, #"verifyProduct.php"]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *receiptDataString = [[NSString alloc] initWithData:receiptData encoding:NSASCIIStringEncoding];
NSString *postData = [NSString stringWithFormat:#"receiptdata=%#", receiptDataString];
[receiptDataString release];
NSString *length = [NSString stringWithFormat:#"%d", [postData length]];
[theRequest setValue:length forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[[NSError alloc] init] autorelease];
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest
returningResponse:&urlResponse
error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
BOOL retVal = NO;
if([responseString isEqualToString:#"YES"])
{
retVal = YES;
}
[responseString release];
return retVal;
}
#end
When the purchase completes, it is up to you to remove the ads. Do something similar to this.
[bannerView removeFromSuperview];
All you have to do is hide the ads when the purchase completes.

Push notification not received in ios5 device

I am sending push notification on device which has iOS 5.0.1, but notification is not received on iOS5 device.
If i try to send notification on iOS4.3.3 device, it received on this device.
My server is developed in c# and apple push notification certificate is used in .p12 format.
My code to register the notification is
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Set the navigation controller as the window's root view controller and display.
deviceToken = nil;
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
[[UIApplication sharedApplication] enabledRemoteNotificationTypes];
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken
{
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:#"Succeeded in registering for APNS" message:#"Sucess" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
[alertView release];
deviceToken = [devToken retain];
NSMutableString *dev = [[NSMutableString alloc] init];
NSRange r;
r.length = 1;
unsigned char c;
for (int i = 0; i < [deviceToken length]; i++)
{
r.location = i;
[deviceToken getBytes:&c range:r];
if (c < 10) {
[dev appendFormat:#"0%x", c];
}
else {
[dev appendFormat:#"%x", c];
}
}
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
[def setObject:dev forKey:#"DeviceToken"];
[def synchronize];
NSLog(#"Registered for APNS %#\n%#", deviceToken, dev);
[dev release];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(#"Failed to register %#", [error localizedDescription]);
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:#"FAILED" message:#"Fail" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
[alertView release];
deviceToken = nil;
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSLog(#"Recieved Remote Notification %#", userInfo);
NSDictionary *aps = [userInfo objectForKey:#"aps"];
NSDictionary *alert = [aps objectForKey:#"alert"];
//NSString *actionLocKey = [alert objectForKey:#"action-loc-key"];
NSString *body = [alert objectForKey:#"body"];
// NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:[self.navigationController viewControllers]];
//
// if ([viewControllers count] > 2) {
// NSRange r;
// r.length = [viewControllers count] - 2;
// r.location = 2;
// [viewControllers removeObjectsInRange:r];
//
// MapViewController *map = (MapViewController*)[viewControllers objectAtIndex:1];
// [map askDriver];
// }
//
// [self.navigationController setViewControllers:viewControllers];
// [viewControllers release];
//NewBooking,"BookingId",Passenger_latitude,Passenger_longitude,Destination_latitude,Destination_longitude,Distance,Time,comments
NSArray *arr = [body componentsSeparatedByString:#","];
if ([arr count]>0) {
MapViewController *map = (MapViewController*)[[self.navigationController viewControllers] objectAtIndex:1];
[map askDriver:arr];
[self.navigationController popToViewController:[[self.navigationController viewControllers] objectAtIndex:1] animated:YES];
}
//NSString *sound = [userInfo objectForKey:#"sound"];
//UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:actionLocKey
// message:body delegate:nil
// cancelButtonTitle:#"Reject"
// otherButtonTitles:#"Accept", nil];
//
// [alertV show];
// [alertV release];
}
Can anyone help me out with this issue. Why notification received on iOS4.3 device but not on iOS5?
Thank you very much!!! in advance
-(void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSLog(#"~~~~devToken=%#",deviceToken);
NSString *dt = [[deviceToken description] stringByTrimmingCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
dt = [dt stringByReplacingOccurrencesOfString:#" " withString:#""];
self.DeviceToken= dt;
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection)
{
NSLog(#"connection exists");
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Connection Error"
message:#"There was an error contacting the servers. Please try again."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
[theConnection release];
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSLog(#"did receive remore notification %#",userInfo);
if(isForground)
{
// your code
}
}
-(void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err
{
NSLog(#"Error in registration. Error: %#", err);
NSString *status = [ NSString stringWithFormat: #"%#\nRegistration failed.\n\nError: %#",[err localizedDescription] ];
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Error" message:status delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}

Device is always showing that failed to regiseter for push notification

Im using the push notification service in my app.
But it is now always showing(when app launches) that it is failed to register for pushnotification.
i used the below code for push notifications:
Can anyone help me where i'm going wrong.
Thanks in advance.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if(application.applicationIconBadgeNumber != 0){
[[[[[self tabBarController] viewControllers] objectAtIndex: 1] tabBarItem] setBadgeValue:#"new"];}
[self.window addSubview:tabBarController.view];
[self.window makeKeyAndVisible];
NSLog(#"Registering for push notifications...");
[[UIApplication sharedApplication]
registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound)];
return YES;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(#"asdfasdf");
NSString *str = [NSString
stringWithFormat:#"Device Token=%#",deviceToken];
const char* data = [deviceToken bytes];
NSMutableString* token = [NSMutableString string];
for (int i = 0; i < [deviceToken length]; i++) {
[token appendFormat:#"%02.2hhX", data[i]];
}
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:#"http://chargrilled.k-hosting.co.uk/test2/register_device.php?dt=%#",token]];
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]autorelease];
NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:self];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Device registered for push notification."
message:nil
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Okay", nil];
[alert show];
[alert release];
}
- (NSString*)stringWithDeviceToken:(NSData*)deviceToken {
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Device registration failed."
message:nil
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Okay", nil];
[alert show];
[alert release];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
int i;
for (id key in userInfo) {
i++;
NSLog(#"key: %#, value: %#", key, [userInfo objectForKey:key]);
if(i==2){
}
}
application.applicationIconBadgeNumber = [[userInfo objectForKey:#"badge"] integerValue];
[[[[[self tabBarController] viewControllers] objectAtIndex: 1] tabBarItem] setBadgeValue:#"new"];
}
Check the profile u are using, is it enable for push notification. If not create a new with push notification.

Adding more than one confirmationalerts (UIAlertView)

Basically, what I try to do is to add multiple confirmationalerts...but I just cant get it to work. No matter what confirmationalert i press, the "Continue" button leads to the exact same thing (a body without text and a subject with "XXXX")...
Any idea how to make the confimationalerts to lead to different things?
EDIT 2; No matter what button I press (continue or dismiss), the app sends the user to mail.app...
-(IBAction)mail {
UIAlertView *mail = [[UIAlertView alloc] init];
[mail setTag:ALERTVIEW_MAIL_TAG];
[mail setTitle:#"Open mail"];
[mail setMessage:#"....."];
[mail setDelegate:self];
[mail addButtonWithTitle:#"Continue"];
[mail addButtonWithTitle:#"Dismiss"];
[mail show];
[mail release];
}
-(IBAction)feedback {
UIAlertView *feedback = [[UIAlertView alloc] init];
[feedback setTag:ALERTVIEW_TIPSA_TAG];
[feedback setTitle:#"Open mail"];
[feedback setMessage:#"....."];
[feedback setDelegate:self];
[feedback addButtonWithTitle:#"Continue"];
[feedback addButtonWithTitle:#"dismiss"];
[feedback show];
[feedback release];
}
- (void)showConfirmAlert
{
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if([alertView tag] == ALERTVIEW_FEEDBACK_TAG) {
NSURL *url = [[NSURL alloc] initWithString:#"mailto:?subject=XXXX"];
[[UIApplication sharedApplication] openURL:url];
[url release];
}
else if (buttonIndex == 1) {
}
else if ([alertView tag] == ALERTVIEW_MAIL_TAG) {
NSString *subject = #"YYYY";
NSString *body = #".....";
NSString *path = [NSString stringWithFormat:#"mailto:?subject=%#&body=%#", subject, body];
NSURL *url = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:url];
}
else if (buttonIndex == 1) {
}
}
You'll need to set a tag on your UIAlertView objects and switch on them in your delegate method, this is why the delegate method takes in the UIAlertView, so you can do stuff based on which object the button was pressed.
#define ALERTVIEW_MAIL_TAG 100
#define ALERTVIEW_FEEDBACK_TAG 101
- (IBAction) feedback {
UIAlertView *feedback = [[UIAlertView alloc] init];
[feedback setTag:ALERTVIEW_FEEDBACK_TAG];
//...
}
- (IBAction) mail {
UIAlertView *mail = [[UIAlertView alloc] init];
[mail setTag:ALERTVIEW_MAIL_TAG];
}
-(void) alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger) buttonIndex {
if([alertView tag] == ALERTVIEW_MAIL_TAG) {
//do stuff...
} else {
//do other stuff...
}
}
The delegate method is specified by the UIAlertViewDelegate protocol, you can't change that.
There are 2 things you can do:
Use 2 different delegates and specify a clickedButtonAtIndex-method for each class.
In the clickedButtonAtIndex-method first check which alertview has sended the message. This requires to tag the UIAlertView (see answer by Jacob Relkin) or to create an instance variable for each UIAlertView.
You should specify which of your buttons is the cancel button, and then you need to check which button was clicked and don't do anything if it was the cancel button. I.e., when you create the alert:
alertView.cancelButtonIndex = 1;
And when you get the button clicked message:
if (buttonIndex == alertView.cancelButtonIndex) return;