Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL is always nil in Swift 3

Tags:

url

swift

swift3

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"
like image 284
PruitIgoe Avatar asked Sep 25 '17 17:09

PruitIgoe


1 Answers

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
like image 141
Rashwan L Avatar answered Dec 25 '22 04:12

Rashwan L