Jack Vanderpump
Jack Vanderpump

Reputation: 486

Instance of a class only returning nil

Fairly new to swift, and struggling with creating an instance of a class within another class. I'm firing a notification and then in my app delegate it responds by playing the music player and changing label in my viewController, but when it tries to change the label app crashes with error "Unexpectedly found nil while implicitly unwrapping an Optional value". I can get round it by adding a '?' but why is it getting nil.

Code

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, AVAudioPlayerDelegate {

var musicPlayerManager: MusicPlayerManager = MusicPlayerManager()
var viewController: ViewController = ViewController()

func application(_ application: UIApplication, didReceive notification: UILocalNotification) {

        //show an alert window
        var playlistName: String = ""
        if let userInfo = notification.userInfo {
            playlistName = userInfo["soundName"] as! String
        }
        musicPlayerManager.playPlaylist(chosenPlaylist: playlistName)
        print(playlistName)
        viewController.currentPlaylist.text = "Playlist: \(playlistName)"

    }

}

I'm getting the playlistName printed in the console, and then it crashes with the last line suggesting that it's an issue with the instance of viewController, and my attempt to change the label in the view controller from the app delegate.

Upvotes: 0

Views: 146

Answers (2)

AMIT
AMIT

Reputation: 924

If you don't want to use storyboard you can create your ViewController in this structure. But you need to add your Subview(currentPlaylist) into your view and also need to set it's frame

import UIKit

class ViewController: UIViewController {
    let currentPlaylist = UILabel()

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    init() {
        super.init(nibName: nil, bundle: nil)

        currentPlaylist.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
        view.addSubview(currentPlaylist)
    }
}

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100503

Outlets are nil until vc loads also you need to load it from storyboard if it exists there

viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "id") as! ViewController 
viewController.view.layoutIfNeeded()
viewController.currentPlaylist.text = "Playlist: \(playlistName)"

Upvotes: 1

Related Questions