Swift Nil Exception on URL

glez

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);
        }
    }
}
Enrique Bermúdez

What happens is that when initizlizing the URL object with the temp string, it can't successfully convert the string into a URL. As URL initializer init?(string: String) is an optional initializer it can return nil if there is an error converting the sting into an URL. Try adding "https://" to you string.

 temp = "https://foo.com?data=" + temp

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related