【问题标题】:iOS local notification: I would like to execute a function upon reentering the app via local notificationiOS本地通知:我想在通过本地通知重新进入应用程序时执行一个功能
【发布时间】:2013-02-15 06:20:29
【问题描述】:

我正在使用 XCode 4.6,并且正在尝试在 iOS 上构建一个本地通知功能,该功能将在重新进入应用程序时执行一个功能。基本上我想更改一些标签中的文本并添加一些声音重新进入应用程序。我以为我走在了正确的轨道上,但是当通过本地通知重新进入应用程序时,我的代码只有部分工作。

首先我将这个函数添加到我的 AppDelegate 中:

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    NSLog(@"test1");   //this traces successfully 
    myAppViewController * controller = [myAppViewController alloc];
    [controller doSomething];  //calling a function in my myAppViewController.m
}

我以为我已经弄明白了,但现在只有 NSLog 在我的 myAppViewController.m 函数中起作用:

-(void)doSomething{
    NSLog(@"do something"); //traces successfully 
    self.notificationTime.text=@"something else"; //nothing happens here, it works in other functions but not here
    [self doSomethingElse]; //calling another function from this function for further testing 
}

调用下一个函数....

-(void)doSomethingElse{
    NSLog(@"do something else"); //this works
    //this whole thing doesn't work -- no sound -- 
    NSURL* url = [[NSBundle mainBundle] URLForResource:@"cash" withExtension:@"mp3"];
    NSAssert(url, @"URL is valid.");
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [self.player prepareToPlay];
    [self.player play];
    //this doesn't work again
    self.notificationTime.text=@"something else";
}

我希望在这里得到一些一般性的建议,我将不胜感激。如果有人知道解决问题的完全不同的方法,那就太好了!

【问题讨论】:

  • 您要更新现有的视图控制器吗?在收到通知之前视图是否可见??

标签: iphone ios objective-c xcode


【解决方案1】:

didReceiveLocalNotification 方法仅在您的应用程序在前台运行时调用。如果您看到一个徽章并单击应用程序启动它,那么您需要使用application:willFinishLaunchingWithOptions:(或application:didFinishLaunchingWithOptions:)处理本地通知要通过这两种方法中的任何一种获取本地通知,请使用UIApplicationLaunchOptionsLocalNotificationKey as选项字典的键。

注意,一旦从启动选项中提取本地通知,调用didReceiveLocalNotification 方法是一种可行的方法。

【讨论】:

    【解决方案2】:

    您不需要分配应用控制器的第二个实例。您可以使用self。如果这样做,代码是否按预期工作?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多