我正在使用 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";
}
我希望能在这里得到一些一般性建议,我将不胜感激。如果有人知道解决问题的完全不同的方法,那也很好!
最佳答案
didReceiveLocalNotification 方法仅在您的应用程序在前台运行时调用。如果你看到一个角标(Badge)并点击 App 启动它,那么你需要使用 application:willFinishLaunchingWithOptions:(或 application:didFinishLaunchingWithOptions:)处理本地通知来获取在这两种方法之一的本地通知中,使用 UIApplicationLaunchOptionsLocalNotificationKey 作为选项字典的键。
请注意,从启动选项中提取本地通知后,调用 didReceiveLocalNotification 方法是一种可行的方法。
关于iphone - iOS本地通知: I would like to execute a function upon reentering the app via local notification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14889307/