swiftnsurlfoundationitunes-api

Why is the URL error occurring?


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()

Solution

  • 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