let url = URL(string: item)! returning nil in swift

Noah Schairer picture Noah Schairer · Jul 28, 2017 · Viewed 8.3k times · Source

Really cannot figure this one out, the URL prints and is not equal to nil, and it works in the browser when I paste it in. Any ideas?

import UIKit

class WebViewController: UIViewController {

    var postLink: String = String()
    @IBOutlet weak var mywebView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        print(postLink)

        let attempt = postLink
        let url: URL = URL(string: attempt)!
        let request: URLRequest = URLRequest(url: url)
        mywebView.loadRequest(request)

    }

The error occurs at:

let url: URL = URL(string: attempt)!

Answer

Lamour picture Lamour · Jul 28, 2017

I am guess you are passing the urlString from another controller, do that instead

var postUrlString:String? //<-- make it optional 

override func viewDidLoad() {
   super.viewDidLoad()

   guard let urlString = postUrlString, // forced unwrapped 
         let url = URL(string: urlString)
        else {  return }  // if there is any optional we return 
 // else continue
        let request: URLRequest = URLRequest(url: url)
        mywebView.loadRequest(request)

}