Mr_Vlasov Mr_Vlasov - 1 year ago 91
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() {

if whichLink == "official link" {

let urlStr = videoGame.offLink!
let url = NSURL(string: urlStr)!
let request = NSURLRequest(URL: url)
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)



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 @

enter image description here

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download