PruitIgoe PruitIgoe - 27 days ago 11
Swift Question

Swift 3: URL is always nil

I have a struct that I am using to call out to the itunes api. But when ever I run it my url variable is never gettng 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