PruitIgoe PruitIgoe - 27 days ago 10
Swift Question

URL is always nil in Swift 3

I have a struct that I am using to call out to the iTunes API. But when ever I run it

myURL
variable is never getting set, it's always
nil
. Not sure what I am doing wrong:

let myDefaultSession = URLSession(configuration: .default)
var myURL: URL?
var myDataTask: URLSessionTask?

struct APIManager {

func getJSON(strURL: String) {
myURL = URL(string: strURL)
var dictReturn: Dictionary<String, Any> = [:]

//cancel data task if it is running
myDataTask?.cancel()
print(myURL!) //<----Always nil
}
}


Here's the string:

"https://itunes.apple.com/search?media=music&entity=song&term=The Chain"

Answer Source

You´re getting nil because the URL contains a space. You need to encode the string first and then convert it to an URL.

func getJSON(strURL: String)  {
    if let encoded = strURL.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
        let myURL = URL(string: encoded) {
       print(myURL)
    }

    var dictReturn:Dictionary<String, Any> = [:]

    //cancel data task if it is running
    myDataTask?.cancel()
}

URL will be:

https://itunes.apple.com/search?media=music&entity=song&term=The%20Chain