Push notification not received in ios5 device - iphone

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];
}

Related

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.

UICGDirectionsDelegate function are not calling in iphone

i display route from start to end point in mapView in iphone and i done it.But after one day i open this project and it does not display route because UICGDirectionsDelegate functions are not called. I dont know why its happen kindly some body guide me about this problem.Many thanks and my sample code is here`
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
if (diretions.isInitialized) {
[self update];
}
routeOverlayView = [[UICRouteOverlayMapView alloc] initWithMapView:mapViews];
diretions = [UICGDirections sharedDirections];
diretions.delegate = self;
}
- (IBAction)backButton:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)update {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
UICGDirectionsOptions *options = [[UICGDirectionsOptions alloc] init];
options.travelMode = travelMode;
if (is_route) {
startPoint = [NSString stringWithFormat:#"%f,%f",APPDELEGATE.user_latitude,APPDELEGATE.user_longitude];
endPoint = [NSString stringWithFormat:#"%#,%#",routeObj.latitude,routeObj.longitude];
destination = poiObj.english_title;
}else {
startPoint = [NSString stringWithFormat:#"%f,%f",APPDELEGATE.user_latitude,APPDELEGATE.user_longitude];
endPoint = [NSString stringWithFormat:#"%# ,%#",poiObj.latitude,poiObj.longitude];
destination = routeObj.starting_poi_name;
}
[diretions loadWithStartPoint:startPoint endPoint:endPoint options:options];
}
- (void)moveToCurrentLocation:(id)sender {
[mapViews setCenterCoordinate:[mapViews.userLocation coordinate] animated:YES];
}
- (void)addPinAnnotation:(id)sender {
UICRouteAnnotation *pinAnnotation = [[UICRouteAnnotation alloc] initWithCoordinate:[mapViews centerCoordinate]
title:nil
annotationType:UICRouteAnnotationTypeWayPoint];
[mapViews addAnnotation:pinAnnotation];
}
#pragma mark <UICGDirectionsDelegate> Methods
- (void)directionsDidFinishInitialize:(UICGDirections *)directions {
[self update];
}
- (void)directions:(UICGDirections *)directions didFailInitializeWithError:(NSError *)error {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Map Directions" message:[error localizedFailureReason] delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
}
- (void)directionsDidUpdateDirections:(UICGDirections *)directions {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
// Overlay polylines
UICGPolyline *polyline = [directions polyline];
NSArray *routePoints = [polyline routePoints];
[routeOverlayView setRoutes:routePoints];
// Add annotations
currentLocation = #"You are here";
UICRouteAnnotation *startAnnotation = [[UICRouteAnnotation alloc] initWithCoordinate:[[routePoints objectAtIndex:0] coordinate]
title:currentLocation
annotationType:UICRouteAnnotationTypeStart];
UICRouteAnnotation *endAnnotation = [[UICRouteAnnotation alloc] initWithCoordinate:[[routePoints lastObject] coordinate]
title:destination
annotationType:UICRouteAnnotationTypeEnd];
[mapViews addAnnotations:[NSArray arrayWithObjects:startAnnotation, endAnnotation, nil]];
}
- (void)directions:(UICGDirections *)directions didFailWithMessage:(NSString *)message {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Map Directions" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
}
`
In UICGRoute.m
Replace this
NSArray *stepDics;
NSDictionary *k;
for (int i = 0; i<allKeys.count; i++) {
k = [dictionaryRepresentation objectForKey:[allKeys objectAtIndex:i]];
if ([k objectForKey:#"Steps"]) {
stepDics = [k objectForKey:#"Steps"];
break;
}
}
with
NSDictionary *k = [dictionaryRepresentation objectForKey:[allKeys objectAtIndex:[allKeys count] - 1]];
NSArray *stepDics = [k objectForKey:#"Steps"];

Want to get my captured video back

I have created a camera using AVFoundation, now i want my video back so i can upload it on my server how can i do that ?
I am using MKNetworkKit for upload video on server.
I am getting output like this:
file://localhost/private/var/mobile/Applications/4B2E02E5-3EE2-493E-8ECF-4B1DA29B9387/tmp/output.mov
Guys I have figured out it by some help here is code for that.
- (void) captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)anOutputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error
{
videodata = [NSData dataWithContentsOfURL:outputFileURL];
//NSLog(#"output file url is :%#",anOutputFileURL);
NSLog(#"output video data size is:%d", videodata.length);
if ([[self delegate] respondsToSelector:#selector(recorder:recordingDidFinishToOutputFileURL:error:)]) {
[[self delegate] recorder:self recordingDidFinishToOutputFileURL:anOutputFileURL error:error];
}
//NSLog(#"captureOutput is: %#",captureOutput);
// NSLog(#"anOutputFileURL is: %#",anOutputFileURL);
//videoPath = [NSString stringWithContentsOfURL:anOutputFileURL encoding:NSUTF8StringEncoding error:nil];
//videoPath = [anOutputFileURL absoluteString];
//videoURL = anOutputFileURL;
// videodata = captureOutput;
// NSLog(#"video path is: %#",videodata);
UIAlertView *message = [[UIAlertView alloc] initWithTitle:nil
message:#"Do you want to upload this content to the yes stream network ?"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Yes",#"No",nil];
[message show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Yes"])
{
NSLog(#"Yes was selected.");
self.flUploadEngine = [[fileUploadEngine alloc] initWithHostName:#"manektech.net" customHeaderFields:nil];
NSMutableDictionary *postParams = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"testApp", #"appID",
nil];
self.flOperation = [self.flUploadEngine postDataToServer:postParams path:#"/dilipvideotest/savefile.php"];
[self.flOperation addData:videodata forKey:#"uploadfile" mimeType:#"video/mov" fileName:#"output.mov" ];
[self.flOperation onCompletion:^(MKNetworkOperation *operation) {
NSLog(#"response string is : %#", [operation responseString]);
/*
This is where you handle a successful 200 response
*/
}
onError:^(NSError *error) {
NSLog(#"error : %#", error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}];
[self.flUploadEngine enqueueOperation:self.flOperation ];
}
else if([title isEqualToString:#"No"])
{
NSLog(#"No was selected.");
//[self readMovie:outputFileURL];
}
}

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.

iphone app exit with "No SIM card installed"

I use the MFMessageComposeViewController for sending in App sms. in iPhone 4.0, if there is no SIM card, the app exits. it just gives a pop up message "no sim card installed".
The delegate callback MessageComposeResultSent. But application exits. Is there any way to prevent it from exiting? or how to check if there is any SIM card in the phone?
Code snippets below:
/* Open the system sms service, copying the sms text in system clipboard. */
- (void) sendSMSAsURLRequest {
NSString *phoneNumber = friend.phoneMobile;
UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
NSString *textUTIType = (NSString *)kUTTypeUTF8PlainText; // add MobileCoreServices.framework for this type.
[pasteBoard setValue:[self buildSMSText] forPasteboardType:textUTIType];
NSString *urlString = [NSString stringWithFormat:#"sms:%#", phoneNumber];
NSURL *url = [[NSURL alloc] initWithString: urlString];
[[UIApplication sharedApplication] openURL: url];
[url release];
}
-(void) sendInAppSMS {
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
controller.delegate = self;
if([MFMessageComposeViewController canSendText])
{
NSString *smsText = [self buildSMSText];
controller.body = smsText;
controller.recipients = [NSArray arrayWithObjects:friend.phoneMobile, nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
switch (result) {
case MessageComposeResultCancelled:
NSLog(#"Cancelled");
break;
case MessageComposeResultFailed:{
NSString *alertString = NSLocalizedString(#"Unknown Error. Failed to send message", #"");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:alertString delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
break;
}
case MessageComposeResultSent:
NSLog(#"SMS sent");
break;
default:
break;
}
[self dismissModalViewControllerAnimated:YES];
}
To Detect Sim Card is installed or not use following Code :
#import CoreTelephony;
CTTelephonyNetworkInfo *networkInfo = [CTTelephonyNetworkInfo new];
CTCarrier *carrier = [networkInfo subscriberCellularProvider];
if (!carrier.isoCountryCode) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"No SIM Card Installed" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
else{
//Paste Your code here
}
The work around I am using now is, a flag in the app delegate,
- (void)applicationWillResignActive:(UIApplication *)aNotification {
if (shouldExitApp) {
exit(0);
}
}
In the SMS sending view controller,
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
((LuupAppDelegate *)[[UIApplication sharedApplication] delegate]).shouldExitApp = NO;
And set the flag again, when in the SMS sending view controller,
- (void) viewDidAppear:(BOOL)animated {
((LuupAppDelegate *)[[UIApplication sharedApplication] delegate]).shouldExitApp = YES;
[super viewDidAppear:animated];
}