ios - 从 View Controller 获取信息到 AppDelegate

标签 ios swift appdelegate

场景如下:

我有一个分析输入声音的 View Controller 。识别出声音后,我会像这样设置本地通知。

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)
}

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

我的 Storyboard是这样的: storyboard

知道我做错了什么吗?

最佳答案

根据您的 Storyboard,self.window?.rootViewController 是 tabbarcontroller。您应该获得 tabbarcontroller 的呈现 View Controller ,它是导航 Controller 之一。然后获取导航 Controller 的呈现 View Controller ,这应该是您分析声音的 View Controller 。

/*** 编辑

由于您使用的是 Storyboard,请尝试使用这段代码(请记住,您为 Storyboard和 View Controller 使用了正确的名称):

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 属性来发送它们。

关于ios - 从 View Controller 获取信息到 AppDelegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29848417/

相关文章:

ios - “AppDelegate”仅适用于 iOS 10.0 或更新版本

ios - 如何将 AppDelegate 的引用发送到 Viewcontroller 子类?

swift - 如何上传具有多个自动ID的新多个节点

ios - AVFoundation:如何获取 AVURLAsset 流式传输的视频的视频尺寸?

ios - 如何防止用户将 UITableViewCell 移动到特定位置?

ios - 如何检测与当前设备的 MCSession 的非编程断开连接?

ios - 无法将表达式的类型 'StaticString' 转换为类型 'StringLiteralConvertible' (Swift)

ios - Swift 如何在 AppDelegate 中发送电子邮件 fetch?

ios - Swift 3 中的 UICollectionView 在部分中显示其他单元格

iOS 通用链接和 URL 缩短器