Mr_Vlasov Mr_Vlasov - 2 months ago 6
Swift Question

"Unexpectedly found nil" but the value is successfully checked with "print". Swift

Getting an "unexpected found nil" error, but when checking the value - its there:

override func viewDidLoad() {
super.viewDidLoad()

if whichLink == "official link" {

let urlStr = videoGame.offLink!
let url = NSURL(string: urlStr)!
let request = NSURLRequest(URL: url)
webView.loadRequest(request)
}
else if whichLink == "moby game link" {

print("yo yo yo, value is here! \(videoGame.mgLink) ")

let urlStr1 = videoGame.mgLink!
let url1 = NSURL(string: urlStr1)!
let request = NSURLRequest(URL: url1)
webView.loadRequest(request)

}

}


I'm suspecting an error in storyboard... but can't locate anything.
Did anyone has a clue what can be wrong?

The full project can be found @ https://github.com/flostik2008/Favorite-Games

enter image description here

Answer

Your URL string is incorrectly formatted with the space at the end, so the NSURL initialization is returning nil.

You should URL encode all raw strings before trying to create an NSURL:

let urlStr1 = videoGame.mgLink!.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! should work