EXC bad access while selecting twitter account from actionsheet in iOS 5 - iphone

I'm now currently fetching the twitter account configured in the device and display in action sheet and when I select a account I get exc bad access error. It crashes in the actionsheet delegate method where I print the twitterArray
#interface LogInViewController ()
{
NSArray *twitterAccountsArray;
ACAccount *selectedAccount;
}
-(void)getTwitterAccountsForLogin
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType
withCompletionHandler:^(BOOL granted, NSError *error) {
if (granted && !error) {
twitterAccountsArray = [accountStore accountsWithAccountType:accountType];
NSLog(#"Account:%#",twitterAccountsArray);
if(twitterAccountsArray == nil || [twitterAccountsArray count] == 0)
{
showAlert(#"Message", TWITTER_NO_ACCOUNT_ERROR , STRING_CONSTANT_OK, nil);
}
else if ([twitterAccountsArray count] > 1)
{
[self performSelectorOnMainThread:#selector(accountListActionSheetDynamics:) withObject:twitterAccountsArray waitUntilDone:YES];
}
else
{
NSLog(#"Only one twitter account so login to that");
}
}
else
{
showAlert(#"Message", TWITTER_ACCESS_DENIED, STRING_CONSTANT_OK, nil);
}
}];
}
- (void)accountListActionSheetDynamics:(NSArray *) accounts {
UIActionSheet *accountsSheet = [[UIActionSheet alloc]
initWithTitle:#"Choose a Twitter Account"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
[accountsSheet setDelegate:self];
for(int i=0;i<accounts.count;i++)
{
[accountsSheet addButtonWithTitle:[[accounts objectAtIndex:i] valueForKey:#"username"]];
}
accountsSheet.cancelButtonIndex = [accountsSheet addButtonWithTitle:#"Cancel"];
[accountsSheet showFromRect:self.view.bounds inView:self.view animated:YES];
NSLog(#"Account:%#",twitterAccountsArray);
}
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == actionSheet.cancelButtonIndex)
{
return;
}
else
{
//Crashes here with exc bad access while printing log
NSLog(#"Account:%#",twitterAccountsArray);
for(int i=0;i<twitterAccountsArray.count;i++)
if([[actionSheet buttonTitleAtIndex:buttonIndex] caseInsensitiveCompare: [[twitterAccountsArray objectAtIndex:i] valueForKey:#"username"]]==NSOrderedSame)
{
selectedAccount = [twitterAccountsArray objectAtIndex:i];
}
}
}
The NSLog(#"Account:%#",twitterAccountsArray); prints fine in the action sheet method and the initial twitter method but crashes in the action sheet delegate method. Any ideas. This happens only in iOS5 works fine for iOS6 and above

I was able to solve the issue by making accountStore and accountType global
#interface LogInViewController ()
{
NSArray *twitterAccountsArray;
ACAccount *selectedAccount;
ACAccountStore *accountStore;
ACAccountType *accountType;
}

Related

Multiple objects in PFQueryTableViewController - Parse.com

I'm trying to display two objects or "classNames" into a PFQueryTableViewController. Here is my code so far with only one object. I can't seem to be able to add more than one object.
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
// Customize the table
// The className to query on
self.className = #"Funny";
//self.className = #"Story";
// The key of the PFObject to display in the label of the default cell style
self.textKey = #"title";
// Whether the built-in pull-to-refresh is enabled
self.pullToRefreshEnabled = YES;
// Whether the built-in pagination is enabled
self.paginationEnabled = YES;
// The number of objects to show per page
self.objectsPerPage = 100;
}
return self;
}
Just add more #propertys to your view controller. Make sure to add the necessary ones (className2, textKey2, etc) and to modify the datasource methods of your table view to display the data.
That being said, it seems strange the the view controller is initiated with initWithCoder. That is usually the method invoked by storyboard for views.
I used two object when saving the post. It worked perfectly!
PFObject *quoteNew = [PFObject objectWithClassName:#"New"];
[quoteNew setObject:[[self attribution] text] forKey:#"by"];
[quoteNew setObject:[[self quoteText] text] forKey:#"quoteText"];
[quoteNew setObject:[[self attributionTitle] text] forKey:#"title"];
[quoteNew saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
[self done:self];
} else {
[[[UIAlertView alloc] initWithTitle:#"Uh oh. Somthing went wrong"
message:[[error userInfo] objectForKey:#"error"]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles: nil] show];
}
}];
PFObject *quote = [PFObject objectWithClassName:#"Funny"];
[quote setObject:[[self attribution] text] forKey:#"by"];
[quote setObject:[[self quoteText] text] forKey:#"quoteText"];
[quote setObject:[[self attributionTitle] text] forKey:#"title"];
[quote saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
[self done:self];
} else {
[[[UIAlertView alloc] initWithTitle:#"Uh oh. Somthing went wrong"
message:[[error userInfo] objectForKey:#"error"]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles: nil] show];
}
}];
}

How to get user details using twitter api v1.1 (Twitter error 215)

I have used the twitter api provided by twitter,to get the details but
not able to execute it, even tried to pass the authentication data
like consumer secret key, consumer key, token but the result is same.
I am able to login and receiving twitter authentication token but not able to get user details.
Below code is used by me (I am using MGtwitter engine) :
NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://api.twitter.com/1.1/users/show.json?screen_name=%#",username]]];
NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *err = nil;
twitterLogin = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
Error is shown as below:
errors = (
{
code = 215;
message = "Bad Authentication data";
} );
First, you need to Authenticate your request (Get permission).
second, see follow these steps:
1.Download FHSTwitterEngine Twitter Library.
2.Add the folder FHSTwitterEngine" to your project and #import "FHSTwitterEngine.h".
3.add SystemConfiguration.framework to your project.
Usage : 1.in the [ViewDidLoad] add the following code.
UIButton *logIn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
logIn.frame = CGRectMake(100, 100, 100, 100);
[logIn setTitle:#"Login" forState:UIControlStateNormal];
[logIn addTarget:self action:#selector(showLoginWindow:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:logIn];
[[FHSTwitterEngine sharedEngine]permanentlySetConsumerKey:#"<consumer_key>" andSecret:#"<consumer_secret>"];
[[FHSTwitterEngine sharedEngine]setDelegate:self];
and don't forget to import the delegate FHSTwitterEngineAccessTokenDelegate.
you need to get the permission for your request, with the following method which will present Login window:
- (void)showLoginWindow:(id)sender {
[[FHSTwitterEngine sharedEngine]showOAuthLoginControllerFromViewController:self withCompletion:^(BOOL success) {
NSLog(success?#"L0L success":#"O noes!!! Loggen faylur!!!");
}];
}
when the Login window is presented, enter your Twitter Username and Password to authenticate your request.
add the following methods to your code:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[FHSTwitterEngine sharedEngine]loadAccessToken];
NSString *username = [[FHSTwitterEngine sharedEngine]loggedInUsername];// self.engine.loggedInUsername;
if (username.length > 0) {
lbl.text = [NSString stringWithFormat:#"Logged in as %#",username];
[self listResults];
} else {
lbl.text = #"You are not logged in.";
}
}
- (void)storeAccessToken:(NSString *)accessToken {
[[NSUserDefaults standardUserDefaults]setObject:accessToken forKey:#"SavedAccessHTTPBody"];
}
- (NSString *)loadAccessToken {
return [[NSUserDefaults standardUserDefaults]objectForKey:#"SavedAccessHTTPBody"];
}
4.Now you are ready to get your request, with the following method(in this method I created a Twitter search for some Hashtag, to get the screen_name for example):
- (void)listResults {
dispatch_async(GCDBackgroundThread, ^{
#autoreleasepool {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// the following line contains a FHSTwitterEngine method wich do the search.
dict = [[FHSTwitterEngine sharedEngine]searchTweetsWithQuery:#"#iOS" count:100 resultType:FHSTwitterEngineResultTypeRecent unil:nil sinceID:nil maxID:nil];
// NSLog(#"%#",dict);
NSArray *results = [dict objectForKey:#"statuses"];
// NSLog(#"array text = %#",results);
for (NSDictionary *item in results) {
NSLog(#"text == %#",[item objectForKey:#"text"]);
NSLog(#"name == %#",[[item objectForKey:#"user"]objectForKey:#"name"]);
NSLog(#"screen name == %#",[[item objectForKey:#"user"]objectForKey:#"screen_name"]);
NSLog(#"pic == %#",[[item objectForKey:#"user"]objectForKey:#"profile_image_url_https"]);
}
dispatch_sync(GCDMainThread, ^{
#autoreleasepool {
UIAlertView *av = [[UIAlertView alloc]initWithTitle:#"Complete!" message:#"Your list of followers has been fetched" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
});
}
});
}
That's all.
I just got the screen_name from a search Query, you can get a timeline for a user using the following methods:
// statuses/user_timeline
- (id)getTimelineForUser:(NSString *)user isID:(BOOL)isID count:(int)count;
- (id)getTimelineForUser:(NSString *)user isID:(BOOL)isID count:(int)count sinceID:(NSString *)sinceID maxID:(NSString *)maxID;
instead of the search method above.
Note: see the FHSTwitterEngine.h to know what method you need to use.
Note: to get the <consumer_key> and the <consumer_secret> you need to to visit this link
to register your app in Twitter.
Got the solution after MKAlatrash revert, to get the user profile follow certain steps in the code as under :
[[FHSTwitterEngine sharedEngine]getProfileImageForUsername:username andSize:FHSTwitterEngineImageSizeNormal];
jump to definition of this function and replace the if ... else if part
if ([userShowReturn isKindOfClass:[NSError class]]) {
return [NSError errorWithDomain:[(NSError *)userShowReturn domain] code:[(NSError *)userShowReturn code] userInfo:[NSDictionary dictionaryWithObject:request forKey:#"request"]];
NSLog(#"user show return %#",userShowReturn);
} else if ([userShowReturn isKindOfClass:[NSDictionary class]]) {
return userShowReturn;
NSString *url = [userShowReturn objectForKey:#"profile_image_url"]; // normal
if (size == 0) { // mini
url = [url stringByReplacingOccurrencesOfString:#"_normal" withString:#"_mini"];
} else if (size == 2) { // bigger
url = [url stringByReplacingOccurrencesOfString:#"_normal" withString:#"_bigger"];
} else if (size == 3) { // original
url = [url stringByReplacingOccurrencesOfString:#"_normal" withString:#""];
}
id ret = [self sendRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
if ([ret isKindOfClass:[NSData class]]) {
return [UIImage imageWithData:(NSData *)ret];
}
return ret;
}
That really was helpful thanks

Handle ACAccountStoreDidChangeNotification for Facebook & Twitter in iOS 6+

I am using Social framework for Facebook & Twitter integration. For this I followed this link
Everything is working fine except when I app receives ACAccountStoreDidChangeNotification , it crashes.
App crashes when
1) I installed app for first time & user don't have Facebook / Twitter account configured in Settings.
2) When I call any method of Facebook / Twitter , it gives me error code 6 as I don't have account configured which is right.
3) I click on HOME button so my app enters background & add account in Settigs.
4) Once I configured account & come back to app , my app launches from background & receives ACAccountStoreDidChangeNotification.
5) In selector of ACAccountStoreDidChangeNotification my account object is nil so my app crashes. So I checked for the nil
Here is my code
#pragma mark - Request Facebook Account Access
-(void)requestFacebookAccountAccess
{
requestType = kNoOpRequest;
// Register for Account Change notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(accountChanged:) name:ACAccountStoreDidChangeNotification object:nil];
self.accountStore = [[ACAccountStore alloc]init];
ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
// Set facebook permissions
NSArray *permissions = nil;
// We need to ask for Basic permission first
if (![kUserDefaults boolForKey:FACEBOOK_BASIC_PERMISSION]) {
permissions = #[#"email",#"user_about_me",#"user_location",#"friends_about_me"];
self.isBasicFacebookPermissionsRequested = YES;
}
else {
permissions = #[#"email",#"user_about_me",#"user_location",#"friends_about_me",#"publish_stream"];
}
//use ACAccountStore to help create your dictionary
NSDictionary *dictFacebook = #{
ACFacebookAppIdKey: kFacebookAppIDKey,
ACFacebookPermissionsKey: permissions,
ACFacebookAudienceKey: ACFacebookAudienceFriends
};
[self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFacebook completion:^(BOOL granted, NSError *error) {
if (granted) {
if (self.isBasicFacebookPermissionsRequested) {
self.isBasicFacebookPermissionsRequested = NO;
[kUserDefaults saveBasicFacebookPermissionsGrantedStatus:YES];
//[self requestFacebookAccountAccess];
}
// User granted permission to Accout
NSArray *accountsArray = [self.accountStore accountsWithAccountType:FBaccountType];
if ([accountsArray count]>0) {
//It will always be the last object with SSO
self.facebookAccount = [accountsArray lastObject];
NSLog(#"In %s::IS MAIN THREAD:- %#",__PRETTY_FUNCTION__,[NSThread isMainThread]?#"YES":#"NO");
if ([self.delegate respondsToSelector:#selector(didFacebookAccountAccessGranted)]) {
dispatch_async(dispatch_get_main_queue(),^{
[self.delegate didFacebookAccountAccessGranted];
});
}
}
else {
[self showAlertWithTitle:#"Error" andMessage:#"You don't have any Facebook accounts set up yet.Please set a Facebbok account and try again."];
}
}
else {
DLog(#"User denied permission to Accout::Localized Error:- %#",error.localizedDescription);
if([error code]==6) {
[self showAlertWithTitle:#"Error" andMessage:#"Please setup facebook account from Settings"];
if ([self.delegate respondsToSelector:#selector(didFacebookAccountAccessDenied:)]) {
dispatch_async(dispatch_get_main_queue(),^{
[self.delegate didFacebookAccountAccessDenied:error];
});
}
}
else if ([self.delegate respondsToSelector:#selector(didFacebookAccountAccessDenied:)]) {
dispatch_async(dispatch_get_main_queue(),^{
[self.delegate didFacebookAccountAccessDenied:error];
});
}
else {
// User denied permission to Account
[self showAlertWithTitle:#"Error" andMessage:[NSString stringWithFormat:#"User denied permission to Accout::Error:- %#",error.localizedDescription]];
}
}
}];
}
#pragma mark - Get Logged In User Info
-(void)getLoggedInUserInfo
{
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/fql"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"SELECT current_location,uid,name,sex,birthday,email,pic FROM user WHERE uid=me()",#"q", nil];
requestType = kGetLoggedInUserInfoRequest;
[self requestDataUsingURL:requestURL parameters:dict requestMethod:SLRequestMethodGET];
}
#pragma mark - Request Data From Facebook
-(void)requestDataUsingURL:(NSURL*)requestURL parameters:(NSDictionary*)params requestMethod:(SLRequestMethod)reuqestMethod
{
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:reuqestMethod
URL:requestURL
parameters:params];
request.account = self.facebookAccount;
[request performRequestWithHandler:^(NSData *data,
NSHTTPURLResponse *response,
NSError *error)
{
NSDictionary *dictData =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(!error)
{
if([dictData objectForKey:#"error"]!=nil)
{
DLog(#"Request Data From Facebook Errro:- %#",dictData);
[self attemptRenewCredentials];
if ([self.delegate respondsToSelector:#selector(didGetFacebookError:)]) {
dispatch_async(dispatch_get_main_queue(),^{
[self.delegate didGetFacebookError:dictData];
});
}
}
else {
// Process the response
//NSLog(#"Response Dictionary contains: %#", dictData );
if ([self.delegate respondsToSelector:#selector(didPostToFacebook:)]) {
dispatch_async(dispatch_get_main_queue(),^{
[self.delegate didPostToFacebook:dictData];
});
}
}
}
else{
if ([self.delegate respondsToSelector:#selector(didGetFacebookError:)]) {
dispatch_async(dispatch_get_main_queue(),^{
[self.delegate didGetFacebookError:dictData];
});
}
else {
[self showAlertWithTitle:#"Error" andMessage:#"Some error occured while processing Facebook request"];
}
}
}];
}
-(void)accountChanged:(NSNotification *)notif
{
if (self.facebookAccount!=nil) {
[self attemptRenewCredentials];
}
else {
[self requestFacebookAccountAccess];
}
}
#pragma mark - Attempt to Renew Credentials
-(void)attemptRenewCredentials
{
[self.accountStore renewCredentialsForAccount:(ACAccount *)self.facebookAccount completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){
if(!error)
{
switch (renewResult) {
case ACAccountCredentialRenewResultRenewed:
NSLog(#"Good to go");
[self againRequestFacebook];
break;
case ACAccountCredentialRenewResultRejected:
NSLog(#"User declined permission");
break;
case ACAccountCredentialRenewResultFailed:
NSLog(#"non-user-initiated cancel, you may attempt to retry");
break;
default:
break;
}
}
else{
//handle error gracefully
NSLog(#"error from renew credentials%#",error);
}
}];
}
-(void)againRequestFacebook
{
switch (requestType) {
case kGetLoggedInUserInfoRequest:
[self getLoggedInUserInfo];
break;
case kGetFriendsInfoRequest:
[self getFacebookFriendsInfo];
break;
case kPostToWallRequest:
[self postToFacebookWallInBackgroundForUserId:fbUserIdForPost withParams:paramsToPost];
break;
default:
break;
}
}
#pragma mark - Remove Observer for Notification
-(void)dealloc
{
requestType = kNoOpRequest;
[[NSNotificationCenter defaultCenter] removeObserver:ACAccountStoreDidChangeNotification];
}
But accountChanged method gets called multiple times.
What is wrong in this ? How can I handle this situation ?
Any kind of help is highly appreciated.
Thanks in advance.
I am facing the same problem...so i used a work around by having a BOOL value in NSUserDefaults to execute accountChanged method only once
-(void)accountChanged:(NSNotification *)notif
{
BOOL calledAccountChanged =[[[NSUserDefaults standardUserDefaults] objectForKey:DidAccountChanged] boolValue];
if(!calledAccountChanged)
{
if (self.facebookAccount!=nil) {
[self attemptRenewCredentials];
}
else {
[self requestFacebookAccountAccess];
}
}
}
Then we can change DidAccountChanged value later in the code...
If you have better solution do post it...

Identifying the Push Notification Message

In my project I want to show the events and offers through push notification, but the problem is, I'm able to show the events or offers, not both. Is there any way to identify the message of Push notification. Here's the code:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSString *message = nil;
id alert = [userInfo objectForKey:#"alert"];
if ([alert isKindOfClass:[NSString class]]) {
message = alert;
} else if ([alert isKindOfClass:[NSDictionary class]]) {
message = [alert objectForKey:#"body"];
}
if (alert) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Title"
message:#"AThe message." delegate:self
cancelButtonTitle:#"button 1"
otherButtonTitles:#"button", nil];
[alertView show];
}
NSString *contentsInfo = [userInfo objectForKey:#"contTag"];
NSLog(#"Received contents info : %#", contentsInfo);
NSString *nibName = [AppDelegate fetchNibWithViewControllerName:#"EventsViewController"];
EventsViewController *evc = [[EventsViewController alloc] initWithNibName:nibName bundle:nil];
evc.newEvent = YES;
[self.navigationController pushViewController:evc animated:YES];
[UIApplication sharedApplication].applicationIconBadgeNumber = [[[userInfo objectForKey:#"aps"] objectForKey: #"badgecount"] intValue];
}
alert is always an NSDictionary with two keys: body and show-view. The value of the former is the alert message and the latter is a Boolean (false or true). If false, the alert’s View button is not shown. The default is to show the View button which, if the user taps it, launches the application.
check the docs
To identify type of the message you can provide additional fields, as described here
Example:
{
"aps":{
"badge":1,
"alert":"This is my special message!",
"mycustomvar1":"123456",
"mycustomvar2":"some text",
"myspecialtext":"This is the best!",
"url":"http://www.mywebsite.com"
}
}

For push notifications: how do I add action to alert view to change views?

So I have push notifications sending to my application.
The code that triggers the alert is in my app delegate file (I think thats where it is supposed to go?)
How do I make an action for my alert button so that I can change to a different view?
// Set Below code in your App Delegate Class...
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
// Call method to handle received notification
[self apnsPayloadHandling:userInfo];
}
-(void) apnsPayloadHandling:(NSDictionary *)userInfo{
// Example Payload Structure for reference
/*
remote notification: {
acme1 = 11114;
aps = {
alert = {
"action-loc-key" = "ACTION_BUTTON_TITLE";
"loc-args" = ("MSG_TEXT");
"loc-key" = "NOTIFICATION_DETAIL_PAGE";
};
badge = 10;
sound = "chime";
};
}
*/
//======================== Start : Fetching parameters from payload ====================
NSString *action_loc_key;
NSArray *loc_args_array;
int badge;
NSString *sound=#"";
NSArray *payloadAllKeys = [NSArray arrayWithArray:[userInfo allKeys]];
// getting "acme1" parameter value...
if([payloadAllKeys containsObject:#"acme1"]){
acme1 = [userInfo valueForKey:#"acme1"]; // getting "ID value" as "acme1"
}
NSString *localizedAlertMessage=#"";
// getting "aps" parameter value...
if([payloadAllKeys containsObject:#"aps"]){
NSDictionary *apsDict = [NSDictionary dictionaryWithDictionary:[userInfo objectForKey:#"aps"]];
NSArray *apsAllKeys = [NSArray arrayWithArray:[apsDict allKeys]];
if([apsAllKeys containsObject:#"alert"]){
if([[apsDict objectForKey:#"alert"] isKindOfClass:[NSDictionary class]]){
NSDictionary *alertDict = [NSDictionary dictionaryWithDictionary:[apsDict objectForKey:#"alert"]];
NSArray *alertAllKeys = [NSArray arrayWithArray:[alertDict allKeys]];
if([alertAllKeys containsObject:#"action-loc-key"]){
action_loc_key = [alertDict valueForKey:#"action-loc-key"]; // getting "action-loc-key"
}
if([alertAllKeys containsObject:#"loc-args"]){
loc_args_array = [NSArray arrayWithArray:[alertDict objectForKey:#"loc-args"]]; // getting "loc-args" array
}
if([alertAllKeys containsObject:#"loc-key"]){
loc_key = [alertDict valueForKey:#"loc-key"]; // getting "loc-key"
}
if([loc_args_array count] == 1){
localizedAlertMessage = [NSString stringWithFormat:NSLocalizedString(loc_key, nil),[loc_args_array objectAtIndex:0]];
}
else if([loc_args_array count] == 2){
localizedAlertMessage = [NSString stringWithFormat:NSLocalizedString(loc_key, nil),[loc_args_array objectAtIndex:0],[loc_args_array objectAtIndex:1]];
}
else if([loc_args_array count] == 3){
localizedAlertMessage = [NSString stringWithFormat:NSLocalizedString(loc_key, nil),[loc_args_array objectAtIndex:0],[loc_args_array objectAtIndex:1],[loc_args_array objectAtIndex:2]];
}
}
else{
localizedAlertMessage = [apsDict objectForKey:#"alert"];
}
}
if([apsAllKeys containsObject:#"badge"]){
badge = [[apsDict valueForKey:#"badge"] intValue]; // getting "badge" integer value
}
if([apsAllKeys containsObject:#"sound"]){
sound = [apsDict valueForKey:#"sound"]; // getting "sound"
}
}
//======================== Start : Handling notification =====================
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateActive){ // application is already open
if(apnsAlert){
apnsAlert = nil;
}
if(action_loc_key){ // View Button title dynamic...
apnsAlert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:#"%# %#",[[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleDisplayName"],NSLocalizedString(#"NOTIFICATION", nil)] message:localizedAlertMessage delegate:self cancelButtonTitle:NSLocalizedString(#"CANCEL", nil) otherButtonTitles: NSLocalizedString(action_loc_key, nil),nil];
}
else{
apnsAlert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:#"%# %#",[[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleDisplayName"],NSLocalizedString(#"NOTIFICATION", nil)] message:localizedAlertMessage delegate:self cancelButtonTitle:NSLocalizedString(#"OK", nil) otherButtonTitles:nil];
}
[apnsAlert show];
}
else{ // application is in background or not running mode
[self apnsViewControllerRedirectingFor_loc_key:loc_key with_acme1:acme1];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
// the user clicked one of the OK/Cancel buttons
if(alertView == apnsAlert){
if (buttonIndex == 1){
[self apnsViewControllerRedirectingFor_loc_key:loc_key with_acme1:acme1];
}
}
}
-(void) apnsViewControllerRedirectingFor_loc_key:(NSString *)loc_key_para with_acme1:(NSString *)acme1_para{
if([loc_key_para isEqualToString:#"NOTIFICATION_DETAIL_PAGE"]){
DetailPageClass *detailPage = [[DetailPageClass alloc] initWithNibName:#"DetailPageClass" bundle:nil];
[self.navigationcontroller pushViewController:detailPage animated:YES]; // use nav controller where you want to push...
}
else if([loc_key_para isEqualToString:#"NOTIFICATION_MAIN_PAGE"]){
}
...
}
To change the title of the button, use the action-loc-key key in the notification dictionary (see this section of the guide).
To do something when the notification is tapped, you can implement a few methods in your app delegate: Handling notifications.