从 View Controller 获取信息到 AppDelegate

Getting information from a View Controller to AppDelegate

场景如下:

我有一个分析输入声音的视图控制器。识别出声音后,我会像这样设置本地通知。

var notification: UILocalNotification = UILocalNotification()
notification.fireDate = NSDate(timeIntervalSinceNow: 0.0)
notification.alertTitle = knn as String
UIApplication.sharedApplication().scheduleLocalNotification(notification)

这会调用 AppDelegate 中的 application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) 函数。

现在,我还想根据用户在通知中选择的内容在数据库中保存一些数据。 我的 AppDelegate 的 didReceiveLocalNotification:

var state: UIApplicationState = application.applicationState
if state == .Active {
    var alert = UIAlertController(title: "Alert", message: notification.alertTitle, preferredStyle: .Alert)
    var correct = UIAlertAction(title: "Correct", style: .Default, handler: { (test) -> Void in
        //create a new sound in context
        var newSound = Sound.createInManagedObjectContext(self.managedObjectContext!, title: notification.alertTitle, zcr: vc.zcrArray, spectralCentroid: vc.scArray, spectralFlatness: vc.sfArray, mfcc: vc.mfccArray, spectralSlope: vc.ssArray)
        var error : NSError?
        self.managedObjectContext!.save(&error)
    })
    var wrong = UIAlertAction(title: "Incorrect", style: .Default, handler: nil)
    alert.addAction(wrong)
    alert.addAction(correct)
    var view = self.window?.rootViewController
    view?.presentViewController(alert, animated: true, completion: nil)
}

为了将值保存到数据库中,我需要从视图控制器中获取它们。但我找不到办法得到它们。我尝试使用 self.window?.rootViewController 来尝试获取正确的视图控制器,但没有成功。我试图存储的变量在上面的代码中称为 vc.zcrArrayvc.mfccArray 等。

我的故事板是这样的:

知道我做错了什么吗?

根据您的故事板self.window?.rootViewController 是tabbarcontroller。您应该获得 tabbarcontroller 的呈现视图控制器,它是导航控制器之一。然后获取导航控制器的呈现视图控制器,这应该是您分析声音的视图控制器。

/*** 编辑

由于您使用的是故事板,请尝试使用这段代码(请记住,您为故事板和视图控制器使用了正确的名称):

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; UIViewController *uvc = [storyboard instantiateViewControllerWithIdentifier:@"Details"]; [self.window.rootViewController presentViewController:uvc animated:YES completion:nil];

编辑 ***/

如果您要保存的值是 property list types,您可以使用本地通知的 userInfo 属性 来发送它们。