I’m new to Swift and writing an app that reads data from a scanner then posts it to a web page. I am taking the data from a text edit field on my main storyboard for now and when I press a lookup button to trigger the following code it throws the below exception. I set a break point and checked the value of temp prior to its use in the URL and its colored in correctly (not nil). If I type into the edit field then the code works fine from then on; opens the page even if I delete the contents of the edit field using the clear icon (x).
I’m at a loss to understand which variable is nil and how to correct or protect the code. Any help would be appreciated.
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
func setStatus(_ status: String)
{
statusLabel.text = status
}
func processRead(_ data: String?)
{
if (data != nil)
{
var temp: String = data!
setStatus(temp)
temp = "foo.com?data=" + temp
let url: URL = URL(string: temp)! // <<<< THROWS EXCEPTION / BREAK POINT
UIApplication.shared.openURL(url)
}
}
UPDATE -- Corrected code --
func setStatus(_ status: String)
{
statusLabel.text = status
}
func processRead(_ data: String?)
{
if (data != nil && !data!.isEmpty)
{
let temp = "https://foo.com/data=" + data!.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!);
if let url = URL(string: temp)
{
setStatus(data!)
UIApplication.shared.openURL(url)
}
else
{
print("Bad URL: " + temp);
}
}
}