Hang Chen
Hang Chen

Reputation: 83

How can I get the text value of TextView from a ViewController using Swift?

class AlertViewController: UITableViewController{
    @IBOutlet weak var alertText: UITextView!
    override func viewDidLoad() {
        super.viewDidLoad()
        alertText.text = "alert"
    }
}

So i want to get the text value inAppDelegate.swift, and I have this:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    let alertText = AlertViewController().alertText
    print(alertText.text)
    return true
}

I got this error

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

Upvotes: 2

Views: 1364

Answers (2)

override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(true)
        print("text:", alertText.text)
}

AppDelegate start before the ViewController

Upvotes: -1

John Luke Garofalo
John Luke Garofalo

Reputation: 140

@IBOutlet weak var alertText: UITextView!

See how you instantiated this as a "weak" variable. That means it's not going to be instantiated unless it's needed. As Ro22e0 said, I'm not sure why you're calling this in the appDelegate but make sure that the class object is instantiated. Also the textField.text value is an optional so check for nil before you try to print it like so

if let alertText = AlertViewController.text {
    print(alertText)
}

Upvotes: -1

Related Questions