为什么没有保存数据?

时间:2015-12-25 22:21:17

标签: ios swift push-notification

当我尝试在某个视图控制器上打开通知时,我收到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

}

2 个答案:

答案 0 :(得分:1)

不要从AppDelegate设置UILable文本。 在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"
}

答案 1 :(得分:0)

从您显示的代码中,PlayerViewController中的dataModel未初始化,因为它是可选的,其值为nil。由于你隐式展开 - dataModel!它会导致崩溃。 首先初始化dataModel,然后使用它来获取所需的值。