是否可以在StoryBoard中的标签中显示最新的推送通知?

时间:2012-12-23 11:02:12

标签: iphone ios uilabel apple-push-notifications appdelegate

我想在我的主要StoryBoard中的标签中显示最新的推送通知我使用此代码在我的AppDelegate.m中显示警告消息:

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    NSDictionary *test =(NSDictionary *)[userInfo objectForKey:@"aps"];
    NSString *alertString =(NSString *) [test objectForKey:@"alert"];
    NSLog(@"String recieved: %@",alertString);


    UIApplicationState state = [[UIApplication sharedApplication] applicationState];

    if (state == UIApplicationStateActive) {
        UIAlertView *alertmessage=[[UIAlertView alloc]initWithTitle:@"Geier"
                                                            message:alertString                                                   delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];


        [alertmessage show];

        AudioServicesPlaySystemSound(1002);


    }

}

我在我的ViewController.m文件latestpush.text = @"%@",alertString;中尝试了这个但是它不起作用。

有人可以帮助我吗?

感谢:)

1 个答案:

答案 0 :(得分:1)

您需要将文本提供给视图控制器。

您可以通过从application:didReceiveRemoteNotification:

内部发送包含警报消息的自定义NSNotification来执行此操作
[[NSNotificationCenter defaultCenter] 
        postNotificationName:@"PushAlertNotification" 
        object:self
        userInfo:@{@"alertString":alertString}];

在视图控制器的viewDidLoad方法中,注册为观察者:

[[NSNotificationCenter defaultCenter] addObserver:self
                                        selector:@selector(updateStoryboard:)
                                        name:@"PushAlertNotification"
                                        object:nil];

并在视图控制器中创建updateStoryboard:方法:

- (void) updateStoryboard:(NSNotification *) notification {
    self.latestpush.text = notification.userInfo[@"alertString"];
}

另一种解决方案是在AppDelegate中创建一个属性,将ViewController作为观察者接收。

AppDelegate.h(将ViewController更改为VC的实际类型)。

@property (nonatomic, weak) ViewController *observer;

在ViewController中创建一个接受NSString的方法,并让该方法更新你的Storyboard。

ViewController.m

-(void)updateStoryboard(NSString *alertString) {
   self.latestpush.text = alertString;
}

此外,在ViewContoller的viewDidLoad方法中,使用appDelegate注册自己:

- (void)viewDidLoad {
    [super viewDidLoad];
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.observer = self;
}

application:didReceiveRemoteNotification:方法中调用updateStoryboard:

[self.observer updateStoryboard:alertString];