2010-12-29 2 views
3

私はタブバーアプリケーションを持っていて、アプリケーションが実行されていなくても、2番目のタブに切り替えて12時にアラートをポップアップしたいとしましょう。UILocalNotificationからNSNotificationを登録するには?

私が正しく動作しUILocalNotificationためのすべてのコードを得たが、その後、私はそれを行うための最善の方法は、アプリデリゲートから通知を掲載することによりだろうと思った:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  

    // Add the tab bar controller's view to the window and display. 
    [window addSubview:tabBarController.view]; 
    [window makeKeyAndVisible]; 

    // Handle launching from a notification when the app is NOT running 
    UILocalNotification *localNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; 
    if (localNotification) { 
     [tabBarController setSelectedIndex:1]; 
     [[NSNotificationCenter defaultCenter] postNotificationName:@"AlertNotification" object:self]; 
    } 
    return YES; 
} 

その後、私のSecondViewController.mに私は持っています:

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popUpAlert:) name:@"AlertNotification" object:nil]; 
} 

しかし、これは動作しません。 SecondViewControllerのviewDidLoadがまだ呼び出されていない間に通知が送信されたと思われます。これを行うことは可能ですか?この場合、NSNotificationCenterを使用する私のアプローチに同意しますか?

ありがとうございます。

答えて

3

私はすぐにテストプロジェクトを作成し、それが(SecondViewControllerはXIBファイルで作成されたと仮定した場合)awakeFromNibに通知登録を入れて取り組んでしまった

- (void)awakeFromNib { 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popUpAlert:) name:@"AlertNotification" object:nil]; 
} 
+0

偉大な、それは完璧に動作します! -removeObserverを呼び出す適切な場所はどこですか?たぶん、viewDidUnloadまたはdealloc? – phi

+0

deallocは通知を登録する直前に – Jilouc

+0

と思われます。その結果、毎回新しい登録が行われます。 –

0

私はそう思います。ビューコントローラをオブザーバとして追加する前に通知をポストしているため、これは機能しません。

もう1つのアプローチは、アプリケーションがローカル通知から開始されたかどうかを示すために、アプリケーションデリゲートにboolプロパティを追加することです。 アプリデリゲートは、アプリのどこからでも[[UIApplication sharedApplication] delegate]でリクエストできます。

+0

しかし、アプリがから開始された場合、私は知っていますローカル通知。私の問題は、メソッドを2番目のタブに呼び出す方法です。今私は何かをしようとしています\t \t [(SecondViewController *)tabBarController.selectedViewController popUpAlert:nil];これまで運がなかった – phi

+0

ああ、私はそれを取得 - 私のSecondViewController -viewDidAppearでpopUpAlertを呼び出すことを意味する、アプリケーションの代理人のブール値がYESに設定されている場合のみ? – phi

+0

はい、それはうまくいくでしょう。 – Felix

0
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes: UIUserNotificationTypeAlert | UIUserNotificationTypeBadge categories:nil]; 
[[UIApplication shareApplication] registerUserNotificationSettings: settings]; 
+2

あなたのコードがユーザーの質問にどのように対処するかについての説明を提供できますか? – Suever

関連する問題