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

variable is never getting set, it's always
. 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
print(myURL!) //<----Always nil

Here's the string:

" 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) {

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

    //cancel data task if it is running

URL will be: