简体   繁体   中英

Passing data between ViewControllers using prepareForSegue not working

so I am basically building a small browser. On one VC you'd put in the link into a textField and use a button to segue to the other VC where the webView is found.

import Foundation
import UIKit

class ViewOne:UIViewController {
    @IBOutlet weak var textField: UITextField!
    @IBAction func clear(sender: AnyObject) {
    textField.text = ""
    }
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "go" {
            let controller:ViewTwo = segue.destinationViewController as! ViewTwo
            controller.textField = self.textField.text! as String
        }
    }
}


import Foundation
import UIKit

class ViewTwo:UIViewController {
@IBOutlet weak var webView: UIWebView!

override func viewDidAppear(animated: Bool) {

    let url = NSURL(string: textField!)
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
        if let urlContent = data {
            let webContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)
            dispatch_async(dispatch_get_main_queue(), { 
                self.webView.loadHTMLString(String(webContent!), baseURL: nil)
            })
        }
    }

    task.resume()

    if textField?.isEmpty == true {
        print("nothing received")
    } else {
        print("\(textField)")
    }

}

var textField:String?
}

It seems like the data won't pass. I get a fatal error saying the NSURLSession found nothing while unwrapping "url".

Don't use NSURL(string: "\\(XXX)") because the description of the string will include that it's optional. Instead just use the string NSURL(string: textField!) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM