Swift 3中的URL总是为零

Pru*_*goe 3 url swift swift3

我有一个结构,我用来调用iTunes API.但是,当我运行它时,myURL变量永远不会被设置,它始终是nil.不确定我做错了什么:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

这是字符串:

"https://itunes.apple.com/search?media=music&entity=song&term=The Chain"
Run Code Online (Sandbox Code Playgroud)

Ras*_*n L 11

你得到nil因为URL包含空格.您需要先对字符串进行编码,然后将其转换为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()
}
Run Code Online (Sandbox Code Playgroud)

网址将是:

https://itunes.apple.com/search?media=music&entity=song&term=The%20Chain
Run Code Online (Sandbox Code Playgroud)