Why is the URL error occurring?

273 Views Asked by At

I am using the iTunes search API, and for testing I am searching for "Angry Birds" and printing the results. But when I convert the urlPath into NSURL I get a nil value. How do I fix this? The urlPath has the link, but it is nil in the url variable. This is the exact error:

fatal error: unexpectedly found nil while unwrapping an Optional value.

var searchTerm: String = "Angry Birds"
var itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
var escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
var urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=software"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!

print("Search iTunes API at URL \(url)")

connection.start()
2

There are 2 best solutions below

0
On BEST ANSWER

stringByAddingPercentEscapesUsingEncoding returns an Optional String, so what you get is actually this:

https://itunes.apple.com/search?term=Optional("Angry+Birds")&media=software

The solution is to safely unwrap the Optional:

if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
    let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=software"
    let url = NSURL(string: urlPath)
    // ...
}

Result:

https://itunes.apple.com/search?term=Angry+Birds&media=software

0
On

NSURL returns nil when URL contain illegal characters like space. Verify that your URlString is correct one.