Post Notification is not called from application didFinishLaunchingWithOptions - objective-c

I am getting push notification from server but my postNotification is not being called. It is correctly entering in if statement which states that type == 1. All the user defaults are correctly stored but the notification is not being called. I put the break point as well as an alert in the function of view controller which is called by the post notification. But it never being called. Here is my code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if(launchOptions != nil)
{
NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil)
{
NSString *type = [dictionary objectForKey:#"type"];
if([[NSString stringWithFormat:#"%#",type]integerValue]==1)
{
[[NSUserDefaults standardUserDefaults]setObject:[[dictionary objectForKey:#"aps"] valueForKey:#"alert"] forKey:#"message"];
[[NSUserDefaults standardUserDefaults]setObject:[dictionary objectForKey:#"senderid"] forKey:#"senderID"];
[[NSUserDefaults standardUserDefaults]setObject:[dictionary objectForKey:#"sendername"] forKey:#"sendername"];
[[NSUserDefaults standardUserDefaults]setObject:[dictionary objectForKey:#"userimage"] forKey:#"pushImage"];
[[NSUserDefaults standardUserDefaults]synchronize];
NSLog(#"message is %#",[[dictionary objectForKey:#"aps"] valueForKey:#"alert"]);
NSLog(#"senderID is %#",[dictionary objectForKey:#"senderid"]);
NSLog(#"sender name is %#",[dictionary objectForKey:#"sendername"]);
[[NSNotificationCenter defaultCenter] postNotificationName:#"pushNotification" object:nil userInfo:launchOptions];
}
}
#ifdef __IPHONE_8_0
if(NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)
{
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
#endif
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeNewsstandContentAvailability;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
application.applicationIconBadgeNumber=0;
[UIApplication sharedApplication].statusBarHidden = NO;
[UIApplication sharedApplication].networkActivityIndicatorVisible=FALSE;
return YES;
}

Find the answer of my own question. Here is the code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[self window] setBackgroundColor:[UIColor whiteColor]];
[FBLoginView class];
self.mainNavigationController = (UINavigationController*)self.window.rootViewController;
if(launchOptions != nil)
{
NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (dictionary != nil)
{
NSString *type = [NSString stringWithFormat:#"%#",[[[dictionary valueForKey:#"aps"] valueForKey:#"json"] valueForKey:#"type"]];
NSLog(#"type is %#",type);
if ([type isEqualToString:#"0"]) // 0 means NOW
{
[[NSUserDefaults standardUserDefaults]setObject:[[[dictionary valueForKey:#"aps"] valueForKey:#"json"] valueForKey:#"yadda_sub_type"] forKey:kYaddaSubType_Push];
[[NSUserDefaults standardUserDefaults]setObject:[[[dictionary valueForKey:#"aps"] valueForKey:#"json"] valueForKey:#"user_id"] forKey:kYaddaUserID_Push];
[[NSUserDefaults standardUserDefaults]setObject:[[[dictionary valueForKey:#"aps"] valueForKey:#"json"] valueForKey:#"yadda_id"] forKey:kYaddaID_Push];
ReciversSideVC *reciverControoler = [[ReciversSideVC alloc]init];
[reciverControoler.navigationController setNavigationBarHidden:YES];
[reciverControoler.navigationController setToolbarHidden:YES];
[AppDelegateClass.mainNavigationController pushViewController:reciverControoler animated:NO];
}
else if ([type isEqualToString:#"1"]) // 1 means LATER
{
if (isCalendarScreenOpen==YES)
{
CalendarVC *calendar = [[CalendarVC alloc]init];
[calendar.navigationController setNavigationBarHidden:YES];
[calendar.navigationController setToolbarHidden:YES];
[AppDelegateClass.mainNavigationController pushViewController:calendar animated:NO];
}
}
else if ([type isEqualToString:#"2"]) // 2 means Remind me
{
LandingPageVC *landing = [[LandingPageVC alloc]init];
[landing.navigationController setNavigationBarHidden:YES];
[landing.navigationController setToolbarHidden:YES];
[AppDelegateClass.mainNavigationController pushViewController:landing animated:NO];
}
else if ([type isEqualToString:#"3"]) // 3 means Reply
{
LandingPageVC *landing = [[LandingPageVC alloc]init];
[landing.navigationController setNavigationBarHidden:YES];
[landing.navigationController setToolbarHidden:YES];
[AppDelegateClass.mainNavigationController pushViewController:landing animated:NO];
}
else if ([type isEqualToString:#"4"]) // 4 means Contacts
{
[[NSUserDefaults standardUserDefaults]setBool:YES forKey:#"flag_CallAPI"];
[[NSUserDefaults standardUserDefaults]synchronize];
ContactDetailVC *contactDetails = [[ContactDetailVC alloc]init];
contactDetails.userID = [[[dictionary valueForKey:#"aps"] valueForKey:#"json"] valueForKey:#"user_id"];
contactDetails.phoneNumberFromServer = [[[dictionary valueForKey:#"aps"] valueForKey:#"json"] valueForKey:#"phone_number"];
[contactDetails.navigationController setNavigationBarHidden:YES];
[contactDetails.navigationController setToolbarHidden:YES];
[AppDelegateClass.mainNavigationController pushViewController:contactDetails animated:NO];
}
}
}
UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif != nil)
{
NSDictionary *NotificationValue = [localNotif.userInfo objectForKey:#"localPushNotification"];
if (NotificationValue != nil)
{
NSLog(#"Run with notification value: %#", NotificationValue);
[[NSUserDefaults standardUserDefaults]setObject:[NotificationValue valueForKey:#"yadda_sub_type"] forKey:kYaddaSubType_Push];
[[NSUserDefaults standardUserDefaults]setObject:[NotificationValue valueForKey:#"user_id"] forKey:kYaddaUserID_Push];
[[NSUserDefaults standardUserDefaults]setObject:[NotificationValue valueForKey:#"yadda_id"] forKey:kYaddaID_Push];
ReciversSideVC *reciverControoler = [[ReciversSideVC alloc]init];
[AppDelegateClass.mainNavigationController pushViewController:reciverControoler animated:NO];
}
}
if(NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)
{
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeNewsstandContentAvailability;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
application.applicationIconBadgeNumber=0;
[UIApplication sharedApplication].statusBarHidden = NO;
[UIApplication sharedApplication].networkActivityIndicatorVisible=FALSE;
return YES;
}

Related

Update UIMutableUserNotificationAction Button Title on Remote Push Notification

I have an app in iOS where I am sending quick surveys to the users. I want to make use of the new funcionality in iOS 8 where the user interacts directly on the push notification. The user will receive the survey question and respond.
I know you have to construct your actions and categories when starting the app. I have written my code and have been able to successfully perform this so far.
Now, the thing is that the text on the action button will change based on the survey question. I am including the keys and text for the action buttons on the JSON I am sending, but I haven't been able to change the action button titles when receiving the notification.
Is there a way to do this? Here is my code:
I define global variables:
//This will help configure the interactive notifications, so that the user can reply to push notification from out of the app
NSString * const notificationCategoryIdent = #"SURVEY";
NSString * const notificationActionPositiveButton = #"POSITIVE_BUTTON";
NSString * const notificationActionNegativeButton = #"NEGATIVE_BUTTON";
In my AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
if(pushNotificationPayload) {
urlPushData2 = #"Application was closed";
[self application:[UIApplication sharedApplication] didReceiveRemoteNotification:pushNotificationPayload];
}
//Registrar tipos de aviso para Push Notifications
//if ([[UIApplication sharedApplication] respondsToSelector:#selector(registerUserNotificationSettings:)]){
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0){ //Before iOS 8
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
UIUserNotificationTypeSound |
UIUserNotificationTypeAlert)];
}
else {
// define notification actions (In case of categorized remote push notifications)
positiveButton = [[UIMutableUserNotificationAction alloc] init];
[positiveButton setActivationMode:UIUserNotificationActivationModeForeground];
[positiveButton setTitle:notificationActionPositiveButton];
[positiveButton setIdentifier:notificationActionPositiveButton];
[positiveButton setDestructive:NO];
// this action wil be executed without necessity of passcode authentication (if locked)
[positiveButton setAuthenticationRequired:NO];
negativeButton = [[UIMutableUserNotificationAction alloc] init];
[negativeButton setActivationMode:UIUserNotificationActivationModeForeground];
[negativeButton setTitle:notificationActionNegativeButton];
[negativeButton setIdentifier:notificationActionNegativeButton];
[negativeButton setDestructive:NO];
// this action wil be executed without necessity of passcode authentication (if locked)
[negativeButton setAuthenticationRequired:NO];
// define Categories (In case of categorized remote push notifications)
UIMutableUserNotificationCategory *actionCategory;
actionCategory = [[UIMutableUserNotificationCategory alloc] init];
[actionCategory setIdentifier:notificationCategoryIdent];
[actionCategory setActions:#[positiveButton, negativeButton]
forContext:UIUserNotificationActionContextDefault];
NSSet *categories = [NSSet setWithObject:actionCategory];
UIUserNotificationType types = (UIUserNotificationTypeAlert|
UIUserNotificationTypeSound|
UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types
categories:categories];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
//Boolean value for temporary app interruptions
temporaryInactivity = FALSE;
return YES;
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
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);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
application.applicationIconBadgeNumber = [[apsInfo objectForKey:#"badge"] integerValue];
self.mainUrl = [userInfo valueForKey:#"url"];
urlPushData = [NSString stringWithFormat:#"%#", mainUrl];
//NSLog(#"urlPushData: %#",urlPushData);
self.mainUrl2 = [userInfo valueForKey:#"url2"];
urlPushData2 = [NSString stringWithFormat:#"%#", mainUrl2];
//NSLog(#"urlPushData2: %#",urlPushData2);
NSString *category = [apsInfo objectForKey:#"category"];
NSLog(#"category: %#", category);
if ([category isEqualToString:notificationCategoryIdent]) {
NSLog(#"button1: %#", [apsInfo objectForKey:#"positiveButton"]);
NSLog(#"button2: %#", [apsInfo objectForKey:#"negativeButton"]);
NSString *stringPositiveButton = [apsInfo objectForKey:#"positiveButton"];
NSString *stringNegativeButton = [apsInfo objectForKey:#"negativeButton"];
[positiveButton setTitle:stringPositiveButton];
[negativeButton setTitle:stringNegativeButton];
}
else {
if (![urlPushData2 isEqualToString:#"Application was closed"]) {
[UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber - 1;
[[NSUserDefaults standardUserDefaults] setObject:urlPushData2 forKey:#"pushNotificationURL"];
[[NSUserDefaults standardUserDefaults] setObject:alert forKey:#"pushNotificationURLName"];
[[NSUserDefaults standardUserDefaults]synchronize];
if (NSClassFromString(#"UIAlertController")) {
//make and use a UIAlertController
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:#"%#",appNameLink]
message:[NSString stringWithFormat:#"Has recibido una nueva nota: %#. ¿Deseas verla?",alert]
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *Cancel = [UIAlertAction actionWithTitle:#"No"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
[UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber - 1;
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"pushNotificationURL"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"pushNotificationURLName"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
];
UIAlertAction *OK = [UIAlertAction actionWithTitle:#"Sí"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
[UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber - 1;
self.url = [[NSUserDefaults standardUserDefaults] objectForKey:#"pushNotificationURL"];
self.urlName = [[NSUserDefaults standardUserDefaults] objectForKey:#"pushNotificationURLName"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"pushNotificationURL"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"pushNotificationURLName"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self setupNavigationControllerApp];
}
];
[alertView addAction:Cancel];
[alertView addAction:OK];
[[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertView animated:YES completion:nil];
}
else {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:[NSString stringWithFormat:#"%#",appNameLink] message:[NSString stringWithFormat:#"Has recibido una nueva nota: %#. ¿Deseas verla?",alert] delegate:self cancelButtonTitle:#"No" otherButtonTitles:#"Sí", nil];
[alertView show];
}
} else {
[UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber - 1;
//self.url = [[NSUserDefaults standardUserDefaults]objectForKey:#"pushNotificationURL"];
self.url = urlPushData2;
self.urlName = alert;
[self setupNavigationControllerApp];
}
}
}
- (void) application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
if ([identifier isEqualToString:notificationActionPositiveButton]) {
//Testing the action button
self.url = #"http://www.google.com";
self.urlName = #"hello";
[self setupNavigationControllerApp];
}
else if ([identifier isEqualToString:notificationActionNegativeButton]) {
//Testing the action button
self.url = #"http://www.yahoo.com";
self.urlName = #"goodbye";
[self setupNavigationControllerApp];
}
// Must be called when finished
completionHandler();
}
And this is my JSON:
{"aps":
{"alert":"Who's your favorite pop singer?",
"badge":1,
"sound":"default",
"category":"SURVEY",
"positiveButton":"Katy Perry",
"negativeButton":"Miley Cyrus"
},
"url":"http://www.pretechmobile.com",
"url2":"http://goo.gl/U9p1y"
}
I am sorry, but you cannot change the title of the buttons dynamically. They are tied to the category in which they are stored when you register for notifications.
A possible workaround could be to present the two options in the text of the message labeled with an 'A' and a 'B' and have your buttons with titles 'Option A' and 'Option B'. Something like this:
---------------------------------
|Who's your favorite pop singer?|
|A: Katy Perry B: Miley Cyrus|
---------------------------------
| Option A | Option B |
---------------------------------
Also, If you have yes/no questions, you can create a category for them with the options 'Yes' and 'No' and label your notifications with this category.
I hope this helps a bit.

How to hide the Alert Box when the internet connectivity is back.?

I have a music player app in which I am checking for internet connectivity when the app is running. When the connectivity is gone, I am showing an alert message and stopping the song. In case if the connectivity is back, I am again playing the song without user doing anything in it, but the problem is I am unable to hide the alert when the song is played back again. Here is the code:
#import "FirstViewController.h"
CM_EXPORT const CMTime kCMTimeZero;
#interface FirstViewController ()
#end
#implementation FirstViewController
#synthesize metadatas;
#synthesize toggleButton;
#synthesize slider;
#synthesize mpVolumeView = _mpVolumeView;
#synthesize viewVolume;
- (void)viewDidLoad
{
toggleIsOn=TRUE;
MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:self.viewVolume.bounds] ;
[self.viewVolume addSubview:volumeView];
[volumeView sizeToFit];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(IBAction)playButtonPressed:(id)sender
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:TRUE forKey:#"FirstPlay"];
[defaults setBool:YES forKey:#"alertShown"];
if(toggleIsOn){
toggleIsOn=!toggleIsOn;
player = nil;
NSString *stringurl = #"";
stringurl = #"http://majestic.wavestreamer.com:6221/listen.pls";
NSURL *url = [NSURL URLWithString:stringurl];
asset = [AVURLAsset URLAssetWithURL:url options:nil];
playerItem = [AVPlayerItem playerItemWithAsset:asset];
player = [AVPlayer playerWithPlayerItem:playerItem];
player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
[playerItem addObserver:self forKeyPath:#"timedMetadata" options:NSKeyValueObservingOptionNew context:nil];
[playerItem addObserver:self forKeyPath:#"status" options:NSKeyValueObservingOptionNew context:nil];
[player play];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:#selector(audioSessionInterrupted:) name:AVAudioSessionInterruptionNotification object:nil];
[self.toggleButton setImage:[UIImage imageNamed:#"reload.png"] forState:UIControlStateNormal];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
else {
[self.toggleButton setImage:[UIImage imageNamed:#"playMusic.png"] forState:UIControlStateNormal];
self->player.rate=0.0;
toggleIsOn=!toggleIsOn;
}
}
- (void)audioSessionInterrupted:(NSNotification *)notification
{
NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey];
NSNumber *interruptionOption = [[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey];
switch (interruptionType.unsignedIntegerValue) {
case AVAudioSessionInterruptionTypeBegan:{
// [self.toggleButton setImage:[UIImage imageNamed:#"playMusic.png"] forState:UIControlStateNormal];
// • Audio has stopped, already inactive
// • Change state of UI, etc., to reflect non-playing state
} break;
case AVAudioSessionInterruptionTypeEnded:{
// • Make session active
// • Update user interface
// • AVAudioSessionInterruptionOptionShouldResume option
if (interruptionOption.unsignedIntegerValue == AVAudioSessionInterruptionOptionShouldResume) {
// Here you should continue playback.
[player play];
}
} break;
default:
break;
}
}
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)audioPlayer
{
[player pause];
}
-(void)audioRecorderEndInterruption:(AVAudioRecorder *)audioPlayer
{
[player play];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:TRUE forKey:#"alertShown"];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
internetReachable = [Reachability reachabilityForInternetConnection];
[internetReachable startNotifier];
// check if a pathway to a random host exists
hostReachable = [Reachability reachabilityWithHostName:#"www.apple.com"];
[hostReachable startNotifier];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context {
[playerItem removeObserver:self forKeyPath:keyPath];
if ([keyPath isEqualToString:#"status"]) {
AVPlayerItem *pItem = (AVPlayerItem *)object;
if (pItem.status == AVPlayerItemStatusReadyToPlay)
{
metadatas.text = #"";
}
}
if ([keyPath isEqualToString:#"timedMetadata"]) {
for (AVAssetTrack *track in playerItem.tracks) {
for (AVPlayerItemTrack *item in player.currentItem.tracks) {
if ([item.assetTrack.mediaType isEqual:AVMediaTypeAudio]) {
NSArray *meta = [playerItem timedMetadata];
for (AVMetadataItem *metaItem in meta) {
NSString *source = metaItem.stringValue;
metadatas.text = source;
}
}
}
}
}
[self.toggleButton setImage:[UIImage imageNamed:toggleIsOn ? #"playMusic.png" :#"stop.png"] forState:UIControlStateNormal];
}
-(IBAction)fbButtonPressed:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://www.facebook.com"];
if (![[UIApplication sharedApplication] openURL:url])
NSLog(#"%#%#",#"Failed to open url:",[url description]);
}
-(IBAction)inButtonPressed:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://www.linkedin.com"];
if (![[UIApplication sharedApplication] openURL:url])
NSLog(#"%#%#",#"Failed to open url:",[url description]);
}
-(IBAction)tweetButtonPressed:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://www.twitter.com"];
if (![[UIApplication sharedApplication] openURL:url])
NSLog(#"%#%#",#"Failed to open url:",[url description]);
}
-(IBAction) sliderChanged:(id)sender
{
}
-(void) checkNetworkStatus:(NSNotification *)notice
{
// called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
switch (internetStatus)
{
case NotReachable:
{
NSLog(#"The internet is down.");
NSLog(#"%d",[defaults boolForKey:#"alertShown"]);
BOOL isAlertShown = [defaults boolForKey:#"alertShown"];
if(isAlertShown)
{
[self showAlert];
}
break;
}
case ReachableViaWiFi:
{
NSLog(#"The internet is working via WIFI.");
BOOL isFirstTimePlayed = [defaults boolForKey:#"FirstPlay"];
if(isFirstTimePlayed)
{
[self playButtonPressed:nil];
}
break;
}
case ReachableViaWWAN:
{
NSLog(#"The internet is working via WWAN.");
[self playButtonPressed:nil];
break;
}
}
}
-(void)showAlert
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:FALSE forKey:#"alertShown"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Alert" message: #"You have lost data connectivity. Please wait while we try to establish the connection again." delegate: nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
- (NSUInteger)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskPortrait;
}
#end
In your method showAlert, you have a reference to the UIAlertView object, alert. Simply save that reference in a property so that you can access it later.
#interface FirstViewController ()
#property (nonatomic, strong) UIAlertView* internetConnectivityAlertView;
#end
-(void)showAlert
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:FALSE forKey:#"alertShown"];
self.internetConnectivityAlertView = [[UIAlertView alloc] initWithTitle:#"Alert"
message:#"You have lost data connectivity. Please wait while we try to establish the connection again."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[self.internetConnectivityAlertView show];
}
When you do get internet connectivity, simply call
if(self.internetConnectivityAlertView)
{
[self.internetConnectivityAlertView dismissWithClickedButtonIndex:0 animated:YES];
self.internetConnectivityAlertView = nil;
}
to dismiss the alert.
See the API Documentation for UIAlertView.

How to remove the UILocalNotification repeat interval?

i added a UILocalNotification with repeat interval of a minute.
how to remove it?
[[UIApplication sharedApplication] cancelAllLocalNotifications];
just copy it under the method didLaunchWithOptions or viewDidLoad or even on your next UILocalNotification code.
- (BOOL)scheduleNotificationOn:(NSDate*) fireDate
text:(NSString*) alertText
action:(NSString*) alertAction
sound:(NSString*) soundfileName
launchImage:(NSString*) launchImage
andInfo:(NSDictionary*) userInfo
{
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = fireDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = alertText;
localNotification.alertAction = alertAction;
localNotification.soundName = soundfileName != nil ? soundfileName : UILocalNotificationDefaultSoundName;
localNotification.alertLaunchImage = launchImage;
localNotification.userInfo = userInfo;
for (UILocalNotification *notification in [self allLocalNotifications]) {
if ([notification.fireDate timeIntervalSinceDate:localNotification.fireDate] == 0 &&
[notification.alertBody isEqualToString:localNotification.alertBody]
) {
return NO;
}
}
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[localNotification release];
return YES;
}
- (NSArray *)allLocalNotifications
{
return [[UIApplication sharedApplication] scheduledLocalNotifications];
}
- (void)cancelLocalNotification:(UILocalNotification *)notification
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
- (void)cancelAllLocalNotifications
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
you should make a unique identifier to remove notification, such as alertBody..
then
- (void)cancelLocalNotificationByAlertBody:(NSString *)alertBody
{
for (UILocalNotification *notification in [self allLocalNotifications]) {
if ([notification.alertBody isEqual:alertBodyString] ) {
[self cancelLocalNotification:notification];
break;
}
}
}
Try with
notification.repeatInterval = NSCalendarUnit(rawValue: 0)
This code is in Swift. Try with the same thing in objective-c.

How can I load a landscape xib using one ViewController file?

I have a universal app. I'm using separate xibs for the portrait and landscape views. I have the app detecting the orientation and changing the value of a BOOL to true when I'm in landscape. I want to know how to load my landscape xib when that BOOL is true. I've tried several different methods to achieve this, but nothing has worked. Any input on this matter would be most appreciated. I can update this post to include any code snippets necessary. Thanks in advance.
edit: I want to do all of this in one ViewController class, and only for the iPad... not the iPhone. I have all that part worked out. I just need to load the landscape xib.
edit: In my viewDidLoad I'm doing this:
if (userDevice.orientation == UIDeviceOrientationLandscapeLeft || userDevice.orientation == UIDeviceOrientationLandscapeRight) {
landscape = YES;
}
Here's my main view controller .m:
#implementation PassportAmericaViewController
#synthesize browseViewButton, webView, mainView, lblMemberName, menuOpen, internetActive, hostActive, isUsingiPad, portrait, landscape;
- (void)viewDidLoad {
menuOpen = NO;
UIDevice* userDevice = [UIDevice currentDevice];
if (userDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) {
isUsingiPad = YES;
}
if (isUsingiPad)
if (userDevice.orientation == UIDeviceOrientationLandscapeLeft || userDevice.orientation == UIDeviceOrientationLandscapeRight) {
landscape = YES;
}
[self checkForKey];
[super viewDidLoad];
[self.navigationController setNavigationBarHidden:YES];
}
-(void)viewWillAppear:(BOOL)animated{
[self.navigationController setNavigationBarHidden:YES];
}
-(void) checkForKey{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int regCheck = [defaults integerForKey:#"registration"];
if (isUsingiPad) {
if (regCheck == 0) {
RegistrationViewController *regView = [[RegistrationViewController alloc]
initWithNibName:#"RegistrationView-iPad" bundle:[NSBundle mainBundle]];
regView.isUsingiPad = YES;
[self.navigationController pushViewController:regView animated:YES];
}else if (regCheck == 1) {
#try {
NSString *mbrFirstName = [defaults objectForKey:#"firstName"];
NSString *mbrLastName = [defaults objectForKey:#"lastName"];
NSMutableString *name = [[NSMutableString alloc] initWithString:mbrFirstName];
[name appendString:#" "];
[name appendString:mbrLastName];
lblMemberName.text = name;
}
#catch (NSException *exception) {
}
}
}else{
if (regCheck == 0) {
RegistrationViewController *regView = [[RegistrationViewController alloc]
initWithNibName:#"RegistrationView" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:regView animated:YES];
}else if (regCheck == 1) {
#try {
NSString *mbrFirstName = [defaults objectForKey:#"firstName"];
NSString *mbrLastName = [defaults objectForKey:#"lastName"];
NSMutableString *name = [[NSMutableString alloc] initWithString:mbrFirstName];
[name appendString:#" "];
[name appendString:mbrLastName];
lblMemberName.text = name;
}
#catch (NSException *exception) {
}
}
}
}
-(IBAction) openBrowseView{
if (isUsingiPad && landscape) {
BrowseViewController *browseView = [[BrowseViewController alloc]
initWithNibName:#"BrowseView-iPadLandscape" bundle:[NSBundle mainBundle]];
browseView.isUsingiPad = YES;
[self.navigationController pushViewController:browseView animated:YES];
}else if (isUsingiPad){
BrowseViewController *browseView = [[BrowseViewController alloc]
initWithNibName:#"BrowseView-iPad" bundle:[NSBundle mainBundle]];
browseView.isUsingiPad = YES;
[self.navigationController pushViewController:browseView animated:YES];
}else{
BrowseViewController *browseView = [[BrowseViewController alloc]
initWithNibName:#"BrowseView" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:browseView animated:YES];
}
}
-(IBAction) openViewMore{
if (isUsingiPad) {
ViewMoreViewController *viewMoreView = [[ViewMoreViewController alloc]
initWithNibName:#"ViewMoreView-iPad" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:viewMoreView animated:YES];
viewMoreView.isUsingiPad = YES;
}else{
ViewMoreViewController *viewMoreView = [[ViewMoreViewController alloc]
initWithNibName:#"ViewMoreView" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:viewMoreView animated:YES];
}
}
-(IBAction) callTollFree:(id)sender {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"tel:8002837183"]];
}
-(IBAction)clickToJoin:(id)sender {
if (isUsingiPad) {
webView = [[WebViewController alloc]
initWithNibName:#"WebView-iPad" bundle:[NSBundle mainBundle]];
webView.url=#"http://www.passport-america.com/Members/JoinRenew.aspx";
[self.navigationController pushViewController:webView animated:YES];
webView.isUsingiPad = YES;
}else {
webView = [[WebViewController alloc]
initWithNibName:#"WebView" bundle:[NSBundle mainBundle]];
webView.url=#"http://www.passport-america.com/Members/JoinRenew.aspx";
[self.navigationController pushViewController:webView animated:YES];
}
}
-(IBAction) iPadContactUs:(id)sender {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: #"mailto:info#passport-america.com"]];
}
-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
if ([animationID isEqualToString:#"slideMenu"]){
UIView *sq = (__bridge UIView *) context;
[sq removeFromSuperview];
}
}
-(void) positionViews {
if (isUsingiPad) {
UIInterfaceOrientation destOrientation = self.interfaceOrientation;
if (destOrientation == UIInterfaceOrientationPortrait || destOrientation == UIInterfaceOrientationPortraitUpsideDown) {
PassportAmericaViewController *homeView2 = [[PassportAmericaViewController alloc]
initWithNibName:#"PassportAmericaViewController-iPad" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:homeView2 animated:YES];
homeView2.isUsingiPad = YES;
homeView2.portrait = YES;
homeView2.landscape = NO;
}else{
PassportAmericaViewController *homeView2 = [[PassportAmericaViewController alloc]
initWithNibName:#"PassportAmericaViewController-iPadLandscape" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:homeView2 animated:YES];
homeView2.isUsingiPad = YES;
homeView2.portrait = NO;
homeView2.landscape = YES;
}
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if (isUsingiPad) {
return YES;
}else{
// Return YES for supported orientations
return NO;
}
}
-(void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration: (NSTimeInterval)duration {
if (isUsingiPad) {
[self positionViews];
}else{
}
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#end
Edit
It looks like you need to do your work here
BOOL isLandscape = UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation);
NSString *nibName = isLandscape ? #"landscapeNibName" : #"portraitNibName";
RegistrationViewController *regView = [[RegistrationViewController alloc] initWithNibName:nibName bundle:[NSBundle mainBundle]];
I'm not sure where you are getting stuck...
- (id)init;
{
BOOL isLandscape = UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation);
NSString *nibName = isLandscape ? #"landscapeNibName" : #"portraitNibName";
self = [super initWithNibName:nibName bundle:nil];
if (self) {
// any other init stuff
}
return self;
}
or if you prefer to name the nib when you instantiate
BOOL isLandscape = UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation);
NSString *nibName = isLandscape ? #"landscapeNibName" : #"portraitNibName";
MyViewController *viewController = [[MyViewController alloc] initWithNibName:nibName bundle:nil];

Delegates in Objective-C

I am trying to explore some codes in Objective-C. I came across an open source program - batch renamer. I was looking at its code and adding my own implementation. There is one thing in this code that I could not understand - I was hoping someone would be able to help me out.
The problem is that there is a renamer delegate "- (void)renamed" and I have no idea how it is called. So, I was wondering how does the program know when to call/use this delegate.
The code is as follows:
#import "ControllerMain.h"
static NSString *addFilesIdentifier = #"addFiles_item";
static NSString *removeFilesIdentifier = #"removeFiles_item";
static NSString *cleanAllIdentifier = #"cleanAll_item";
static NSString *updateUrl = #"http://www.hardboiled.it/software/update.xml";
#implementation ControllerMain
- (id)init
{
self = [super init];
//init some object
tableSource = [[NSMutableArray alloc] init];
updater = [[STUpdateChecker alloc] init];
renamer = [[STRenamer alloc] init];
//set some variables
withExt = NO;//for include the extension in the renaming, default NO
renamed = NO;//is YES after renaming preview
insoverappPosition = 0;
//set the notification for NSControlTextDidChangeNotification
NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:#selector(textDidEndEditing:) name:#"NSControlTextDidChangeNotification" object:nil];
return self;
}
-(void)awakeFromNib
{
//set the delegates
[tabella setDelegate:self];
[tableSource setDelegate:self];
[renamer setDelegate:self];
[updater setDelegate:self];
//check if the software is updated
[updater checkUpdateWithUrl:[NSURL URLWithString:updateUrl]];
//drag' drop - set the dragged types
[tabella registerForDraggedTypes:[NSArray arrayWithObjects: NSFilenamesPboardType, nil]];
//toolbar configuration
toolbar = [[NSToolbar alloc] initWithIdentifier:#"toolbar"];
[toolbar setDelegate:self];
//mainWindows properties
[mainWindow center];
[mainWindow setTitle:#"macXrenamer"];
[mainWindow setToolbar:toolbar];
//set the extension checkbox
[extSwitch setState:0];
//Set the custom cell imageAndTextCell
ImageAndTextCell *imageAndTextCell = nil;
NSTableColumn *tableColumn = nil;
tableColumn = [tabella tableColumnWithIdentifier:#"original_name"];
imageAndTextCell = [[[ImageAndTextCell alloc] init] autorelease];
[imageAndTextCell setEditable: NO];
[tableColumn setDataCell:imageAndTextCell];
//
//initialize the window for empty table
[self tableSourceIsEmpty];
//release the toolbar
[toolbar release];
}
- (void)dealloc
{
//release all
[tabella unregisterDraggedTypes];
[tableSource release];
[renamer release];
[super dealloc];
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
{
//close the application
return YES;
}
/* ################### tableSource delegates #################################*/
- (void)tableSourceIsEmpty
{
if (KDEBUG)
NSLog(#"tablesource is empty");
[upper_lower setEnabled:NO];
[from setEditable:NO];
[to setEditable:NO];
[insertText setEditable:NO];
[insertAtPosition setEditable:NO];
[insertAtPosition setIntValue:0];
[renameButton setEnabled:NO];
[annullButton setEnabled:NO];
[searchField setEditable:NO];
[replaceField setEditable:NO];
}
- (void)tableSourceIsNotEmpty
{
if (KDEBUG)
NSLog(#"tablesource is not empty");
[upper_lower setEnabled:YES];
[from setEditable:YES];
[to setEditable:YES];
[insertText setEditable:YES];
[insertAtPosition setEditable:YES];
[searchField setEditable:YES];
[replaceField setEditable:YES];
}
-(void)tableSourceDidChange
{
NSString *countString = [NSString stringWithFormat:#"%d files",[tableSource count]];
[number_of_files setStringValue:countString];
}
/*####################end tableSource delegates###############################*/
/*######################renamer delegates#####################################*/
- (void)renamed
{
NSLog(#"renaming preview ok");
NSTabViewItem *tabItem;
tabItem = [tabView selectedTabViewItem];
id tabViewId = [tabItem identifier];
if ([tabViewId isEqual:#"insert"]) {
[insertAtPosition setTextColor:[NSColor blackColor]];
}else if([tabViewId isEqual:#"remove"])
{
[from setTextColor:[NSColor blackColor]];
[to setTextColor:[NSColor blackColor]];
}
renamed = YES;
[renameButton setEnabled:YES];
[annullButton setEnabled:YES];
}
- (void)notRenamed
{
renamed = NO;
NSTabViewItem *tabItem;
tabItem = [tabView selectedTabViewItem];
id tabViewId = [tabItem identifier];
if ([tabViewId isEqual:#"insert"]) {
[insertAtPosition setTextColor:[NSColor redColor]];
}else if([tabViewId isEqual:#"remove"])
{
[from setTextColor:[NSColor redColor]];
[to setTextColor:[NSColor redColor]];
}
NSLog(#"exception in preview delegate");
[renameButton setEnabled:NO];
}
/* ###################end renamer delegates ##################################*/
//make the file extension editable
-(IBAction)makeExtEditable:(id)sender
{
if (KDEBUG)
NSLog(#"makeExtEditable action");
if ([sender state] == 0) {
withExt = NO;
}else if ([sender state] == 1) {
withExt = YES;
}
}
//add files to the table
-(IBAction)addFiles:(id)sender
{
//start the progression bar
[progBar startAnimation:self];
int result;
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
[oPanel setCanChooseFiles:YES];
[oPanel setAllowsMultipleSelection:YES];
[oPanel setResolvesAliases:NO];
result = [oPanel runModalForTypes:nil];
if (result == NSOKButton) {
NSArray *filesToOpen = [oPanel filenames];
[tableSource add:filesToOpen];
[tabella reloadData];
}
//stop the progression bar
[progBar stopAnimation:self];
}
//remove files from the table
-(IBAction)removeFiles:(id)sender
{
if(KDEBUG)
NSLog(#"remove the selected file from the table");
[progBar startAnimation:self];
NSIndexSet *selected = [tabella selectedRowIndexes];
[tableSource removeAtIndexes:selected];
[tabella reloadData];
[progBar stopAnimation:self];
}
//remove all files from the table
-(IBAction)clearTable:(id)sender
{
if(KDEBUG)
NSLog(#"clear all table");
[progBar startAnimation:self];
[tableSource cleanAll];
[tabella reloadData];
[progBar stopAnimation:self];
}
//annull
-(IBAction)annulRenaming:(id)sender
{
[tableSource annull];
NSTabViewItem *tabItem;
tabItem = [tabView selectedTabViewItem];
id tabViewId = [tabItem identifier];
if ([tabViewId isEqual:#"insert"]) {
[insertAtPosition setTextColor:[NSColor blackColor]];
}else if([tabViewId isEqual:#"remove"])
{
[from setTextColor:[NSColor blackColor]];
[to setTextColor:[NSColor blackColor]];
}
renamed = NO;
[renameButton setEnabled:NO];
[tabella reloadData];
}
/*###########################log section######################################*/
-(IBAction)showLogWindows:(id)sender{
if ([logWindow isVisible]) {
[logWindow setIsVisible:FALSE];
}else {
[logWindow setIsVisible:TRUE];
}
}
-(void)addToLog:(NSString *)text
{
NSString *textLog = [text stringByAppendingString:#"\n\r"];
NSRange endRange;
endRange.location = [[logField textStorage] length];
endRange.length = 0;
[logField replaceCharactersInRange:endRange withString:textLog];
endRange.length = [textLog length];
[logField scrollRangeToVisible:endRange];
}
/*#######################end log section######################################*/
/*######################editing actions#######################################*/
-(IBAction)finalRenaming:(id)sender
{
if(KDEBUG)
NSLog(#"renaming button pressed");
//start the progression bar
[progBar startAnimation:self];
//count of the files really renamed
int countRenamed = 0;
//count of the renaming error
int errRenamed = 0;
//the result of rename()
int renameResult;
//the enumerator and the obj
NSEnumerator *en = [tableSource objectEnumerator];
id row;
if(renamed)
{
while(row = [en nextObject])
{
renameResult = rename([[row objectAtIndex:0] fileSystemRepresentation], [[row objectAtIndex:1] fileSystemRepresentation]);
if(renameResult == 0){
NSString *textLog = [NSString stringWithFormat:#"%# renamed with\n %#", [row objectAtIndex:0],[row objectAtIndex:1]];
NSLog(textLog);
[self addToLog:textLog];
countRenamed++;
}else {
NSString *textLog =[NSString stringWithFormat: #"Error in file renaming %#", [row objectAtIndex:0]];
NSLog(textLog);
[self addToLog:textLog];
errRenamed++;
}
}
if(errRenamed >0){
//open the panel alert
int result;
result = NSRunAlertPanel(#"Renaming error. Please check the log", #"Error!", #"Ok", NULL, NULL);
}
//print the result of renaming
[notiField setStringValue:[NSString stringWithFormat:#"renamed %d/%d files, %d errors", countRenamed,[tableSource count],errRenamed]];
//
[tableSource reinitialize];
[tabella reloadData];
[renameButton setEnabled:NO];
[annullButton setEnabled:NO];
[progBar stopAnimation:self];
}
}
- (void)textDidEndEditing:(NSNotification *)aNotification
{
[progBar startAnimation:self];
NSTabViewItem *tabItem;
tabItem = [tabView selectedTabViewItem];
id tabViewId = [tabItem identifier];
if ([tabViewId isEqual:#"insert"]) {
if(KDEBUG)
NSLog(#"insert selected");
if(insoverappPosition == 1)
{
if(KDEBUG)
NSLog(#"overwrite selected");
tableSource = [renamer overwriteChar:tableSource insertText:[insertText stringValue] position:[insertAtPosition intValue] withExt:withExt];
}else if(insoverappPosition == 0){
if(KDEBUG)
NSLog(#"insert selected");
tableSource = [renamer insertChar:tableSource insertText:[insertText stringValue] position:[insertAtPosition intValue] withExt:withExt];
}else if(insoverappPosition == 2){
if(KDEBUG)
NSLog(#"append selected");
tableSource = [renamer appendChar:tableSource appendText:[insertText stringValue] withExt:withExt];
}
}else if ([tabViewId isEqual:#"remove"]) {
if(KDEBUG)
NSLog(#"remove selected");
tableSource = [renamer removeChar:tableSource from:[from intValue] to:[to intValue] withExt:withExt];
}else if([tabViewId isEqual:#"search"]){
if(KDEBUG)
NSLog(#"search selected");
tableSource = [renamer searchAndReplace:tableSource string:[searchField stringValue] withString:[replaceField stringValue] withExt:withExt];
}
[progBar stopAnimation:self];
}
-(IBAction)upLowerCellClicked:(id)sender
{
NSCell* cell;
cell = [upper_lower selectedCell];
int tag = [cell tag];
if (tag == 0) {
if(KDEBUG)
NSLog(#"lowercase selected");
tableSource = [renamer makeLowerCase:tableSource withExt:withExt];
[renameButton setEnabled:YES];
[annullButton setEnabled:YES];
[tabella reloadData];
}
else if(tag == 1){
if(KDEBUG)
NSLog(#"uppercase selected");
tableSource = [renamer makeUpperCase:tableSource withExt:withExt];
[renameButton setEnabled:YES];
[annullButton setEnabled:YES];
[tabella reloadData];
}
}
-(IBAction)insertOverwriteClicked:(id)sender
{
if(KDEBUG)
NSLog(#"insertOverwriteClicked");
NSCell* cell;
cell = [insert_overwrite selectedCell];
int tag = [cell tag];
if(tag == 0)
{
if(KDEBUG)
NSLog(#"insert");
[insertAtPosition setEnabled:YES];
insoverappPosition = 0;
}else if(tag==1){
if(KDEBUG)
NSLog(#"overwrite");
[insertAtPosition setEnabled:YES];
insoverappPosition = 1;
}else if (tag==2) {
if(KDEBUG)
NSLog(#"append");
[insertAtPosition setEnabled:NO];
insoverappPosition = 2;
}
}
/*################end editing actions#########################################*/
-(void)newUpdateIsOnline
{
NSLog(#"newUpdateIsOnline");
BOOL retval;
retval = (NSAlertDefaultReturn == NSRunAlertPanel(#"Update Available", #"Update now or later", #"Update", #"Cancel", nil, nil));
if(retval){
if(KDEBUG)
NSLog(#"update now");
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:#"http://www.hardboiled.it/software/rinominatore-upgrade.zip"]];
//to edit
//[[NSNotificationCenter defaultCenter] postNotificationName:#"openSheetNotification" object:self userInfo:nil];
}else {
if(KDEBUG)
NSLog(#"cancel the update");
}
//release the updater. now is useless
[updater release];
}
/*################nstableview delegates#######################################*/
- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
return [tableSource count];
}
- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
if ([[aTableColumn identifier] isEqualToString: #"original_name"]) {
id obj = [tableSource objectAtRow:rowIndex atIndex:0] ;
return [obj lastPathComponent];
//return theIcon;
}else if([[aTableColumn identifier] isEqualToString: #"new_name"]){
id obj = [tableSource objectAtRow:rowIndex atIndex:1] ;
return [obj lastPathComponent];
}
return nil;
}
- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
if(cell_with_icon)
{
if ( [[aTableColumn identifier] isEqualToString:#"original_name"] ){
[((ImageAndTextCell*) cell) setImage:[tableSource objectAtRow:rowIndex atIndex:2]];
}
}
}
/* ###############end nstableview delegates #################################*/
/*############### nstoolbar delegates #######################################*/
- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
{
return [NSArray arrayWithObjects:addFilesIdentifier,
removeFilesIdentifier,cleanAllIdentifier,
NSToolbarFlexibleSpaceItemIdentifier,
NSToolbarSpaceItemIdentifier,
NSToolbarSeparatorItemIdentifier, nil];;
}
- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *)toolbar
{
return [NSArray arrayWithObjects:addFilesIdentifier,
removeFilesIdentifier,NSToolbarFlexibleSpaceItemIdentifier,cleanAllIdentifier, nil];
}
- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
{
NSToolbarItem *toolbarItem = nil;
if ([itemIdentifier isEqualTo:addFilesIdentifier]) {//button addfiles
toolbarItem = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
[toolbarItem setLabel:#"Add"];
[toolbarItem setPaletteLabel:[toolbarItem label]];
[toolbarItem setToolTip:#"Add"];
[toolbarItem setImage:[NSImage imageNamed:#"add.icns"]];
[toolbarItem setTarget:self];
[toolbarItem setAction:#selector(addFiles:)];
}else if ([itemIdentifier isEqualTo:removeFilesIdentifier]) {//button remove files
toolbarItem = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
[toolbarItem setLabel:#"Remove"];
[toolbarItem setPaletteLabel:[toolbarItem label]];
[toolbarItem setToolTip:#"Remove"];
[toolbarItem setImage:[NSImage imageNamed:#"remove.icns"]];
[toolbarItem setTarget:self];
[toolbarItem setAction:#selector(removeFiles:)];
}else if ([itemIdentifier isEqualTo:cleanAllIdentifier]) {//button clean
toolbarItem = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
[toolbarItem setLabel:#"Clean All"];
[toolbarItem setPaletteLabel:[toolbarItem label]];
[toolbarItem setToolTip:#"Clean the table"];
[toolbarItem setImage:[NSImage imageNamed:#"cleanAll.icns"]];
[toolbarItem setTarget:self];
[toolbarItem setAction:#selector(clearTable:)];
}
return [toolbarItem autorelease];
}
/*###############end nstoolbar delegates #####################################*/
/*################drag'n drop delegates #####################################*/
- (BOOL)tableView:(NSTableView *)tv writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard*)pboard {
// Drag and drop support
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
[pboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType] owner:self];
[pboard setData:data forType:NSFilenamesPboardType];
return YES;
}
- (NSDragOperation)tableView:(NSTableView*)tv validateDrop:(id <NSDraggingInfo>)info proposedRow:(int)row proposedDropOperation:(NSTableViewDropOperation)op
{
// Add code here to validate the drop
if (KDEBUG)
NSLog(#"validate Drop");
return NSDragOperationEvery;
}
- (BOOL)tableView:(NSTableView*)tv acceptDrop:(id )info row:(int)row dropOperation:(NSTableViewDropOperation)op
{
if (KDEBUG)
NSLog(#"acceptDrop");
NSPasteboard *pboard = [info draggingPasteboard];
if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
[tableSource add:files];
}
[tabella reloadData];
return YES;
}
/*################end drag'n drop delegates ##################################*/
#end
The delegate is the object, not the method. The ControllerMain object is set as some other object's delegate. When that other object sees the condition that tells it renaming has occurred (whatever that means), it executes something along the lines of [[self delegate] renamed], which calls the ControllerMain method.