【发布时间】:2019-04-19 05:26:45
【问题描述】:
我有一个简单的应用程序,当用户点击本地推送通知时,它会更新 UILabel。在模拟器中,当我点击通知时,会调用 applicationDidBecomeActive ,其中,我有一个引用视图控制器类的共享对象。然后我调用该类中的函数来获取新字符串并将 UILabel 设置为所述字符串。
这在模拟器中一直有效,但是当我将应用程序加载到我的设备上时,它会在前几次有效,然后停止。
我知道设备正在更新字符串值,因为当我切换到应用程序中的另一个视图并切换回来时,UILabel 现在会显示正确更新的值,但从通知返回时不会显示。
有没有其他人遇到过模拟器和物理设备行为不同的问题?
这里的要求是一些希望有帮助的代码:
这是来自 appDelagate.swift 文件
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
fetchCurrentUnQuoteFromViewController()
print("applicationDidBecomeActive has finished running.")
}
//Custom functions for the delagate
func setDefaultToTrue() {
readyForNewUnQuote = true
defaults.setValue(readyForNewUnQuote, forKey: "readyForNewUnQuote")
}
func fetchCurrentUnQuoteFromViewController() {
let quoteViewController:QuoteViewController = window!.rootViewController as! QuoteViewController
quoteViewController.getRandomGradient()
quoteViewController.fetchRandomUnQuote()
}
在我的视图控制器中,这里是从 appDelagate 调用的函数
func getRandomGradient() {
let randomNumber: Int = Int.random(in: 0 ... gradientArray.count - 1)
QuoteGradient.image = UIImage(named: gradientArray[randomNumber])
}
func updateUI() {
unQuoteLabel.text = defaults.string(forKey: "currentQuote")
}
编辑:我基本上添加了 viewController.viewDidLoad() 作为一个额外的调用,这似乎是有效的。这是一个糟糕的电话吗?这似乎是一种解决问题的骇人听闻的方式。
好的,我想我已经进一步缩小了范围。我有第二个视图,我试图将其用于设置页面。如果我只保留引用文本的第一个视图,那么当弹出通知时,我可以点击它,它将更新为设置的新文本。
但是,如果我转到设置视图然后返回报价视图,那么当我点击通知时它不会更新文本,直到我返回设置页面然后再次返回报价页面。
我是 iOS 开发的新手,我真的不知道转到新视图是否会对我正在创建的共享对象产生任何影响,或者它是否会产生我不知道的其他事情。
编辑 2:这是用户点击通知时触发的函数:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
setDefaultToTrue()
print(defaults.value(forKey: "readyForNewUnQuote") ?? "Error")
fetchCurrentUnQuoteFromViewController()
print("response from notification was fired.")
completionHandler()
}
【问题讨论】:
-
您必须提供一些代码。是的,模拟器和物理设备在某些方面确实表现不同。
-
@MikeTaverne 我已经用一些代码更新了我的问题,希望对这项调查有所帮助。
-
如果应用程序被终止,那么您可能需要签入 didFinishLaunching。您可以在那里检查有效负载。我相信您可以检查一些问题
-
@agibson007 发生这种情况时,应用程序不会被杀死。它只是在后台处于非活动状态。
-
@Puddinglord didReceiveLocalNotification 函数在哪里。你也应该在那里处理事情。
标签: ios swift ios-simulator