尝试在某个视图控制器上打开通知时出现fatal error: unexpectedly found nil while unwrapping an Optional value
。我想我知道为什么,有些变量为零,导致应用崩溃,但是我正在尝试为这些变量提供数据,但它们没有保存。
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
let text = userInfo["aps"]!["alert"]
let title = userInfo["aps"]!["alert"]!!["title"]
let artist = userInfo["aps"]!["alert"]!!["artist"]
print(text)
print(title)
print(artist)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("PlayerController") as! PlayerViewController
vc.dataModel.artistplay = artist as? String
vc.dataModel.titleplay = title as? String
window?.rootViewController = vc
}
这是PlayerViewController的代码(在打开通知时我试图打开的视图控制器)
@IBOutlet weak var playertitle: UILabel!
@IBOutlet weak var playerartist: UILabel!
var dicData : NSDictionary?
var dataModel : DataModelTwo?
var data: NSDictionary?
var shareDataModel: Share?
var buttonState: Int = 0;
override func viewWillAppear(animated: Bool) {
playertitle.text = dataModel!.titleplay
playerartist.text = dataModel!.artistplay
}
最佳答案
不要从AppDelegate设置UILabel文本。
在ViewController中设置一个变量,然后在viewDidLoad
中使用它。
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
let text = userInfo["aps"]!["alert"]
print(text)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("PlayerController") as! PlayerViewController
vc.foo = "bar"
window?.rootViewController = vc
}
使用变量并更新UI:
override func viewDidLoad() {
print(self.foo) // output is "bar"
}