Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

I'm creating a code where someone scans a barcode, and it then sends them to a website by adding the EAN/UPC to the end of a URL. However, I am greeted with an error on line 37. I have no idea how to fix this 🤦🏻‍♂️, please help! Thanks in advance.

Answered by Claude31 in 747967022

That's because the string is not valid for URL:

Link(destination:URL(string:"https://www.sites.google.com/view/planete-app/database/\(scannedCode)")!

You should print before and tell what you get.

print("https://www.sites.google.com/view/planete-app/database/\(scannedCode)")

to see what you get and test this URL directly in a browser

Maybe you have spaces in string.

Then replace

"https://www.sites.google.com/view/planete-app/database/\(scannedCode)" 

by:

"https://www.sites.google.com/view/planete-app/database/\(scannedCode)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

Note: it is always risky to unwrap an optional without testing for nil

Accepted Answer

That's because the string is not valid for URL:

Link(destination:URL(string:"https://www.sites.google.com/view/planete-app/database/\(scannedCode)")!

You should print before and tell what you get.

print("https://www.sites.google.com/view/planete-app/database/\(scannedCode)")

to see what you get and test this URL directly in a browser

Maybe you have spaces in string.

Then replace

"https://www.sites.google.com/view/planete-app/database/\(scannedCode)" 

by:

"https://www.sites.google.com/view/planete-app/database/\(scannedCode)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

Note: it is always risky to unwrap an optional without testing for nil

Please post code here as formatted text, not screenshots. Would be easy to copy the code and test myself, but no one will try to write that code to try out what is the issue.

Also, post the error also as text, we cannot see from the picture what the error is. Is that a compiler error or runtime error? Compiler doesn't check the URL for correctness so if the URL is incorrect, that would be a runtime error then?

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
 
 
Q