简体   繁体   中英

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

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)!

The error is simple, postLink , you are providing to create URL is not correct. My guess is its empty.(Just a guess) and you have forgot to set it.

Avoid using force unwrapping ! in your code as much as possible. You should either use guard let or if let in the scenarios. In your case you might want to show some error to user when you are unable to load. Instead of

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

use

    if let url = URL(string: attempt) {
        let request = URLRequest(url: url)
        mywebView.loadRequest(request)
    } else {
// Do something like. Show an alert that could not load webpage etc. 
}

Alternatively you can use guard let , but it would require to return from the function where it is used. To know more about uses of if and guard let you can go through by blog post here .

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)

}

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