URL在Swift中始终为零3

问题描述:

我有一个用于调用iTunes API的结构。但是,当我运行它myURL变量永远不会被设置,它总是nil。不知道我做错了:URL在Swift中始终为零3

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 
    } 
} 

这里的字符串:

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

后的字符串you're传递到的getJSON –

+0

https://itunes.apple.com/search?media=music&entity=song&term=The链 – PruitIgoe

You're越来越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() 
} 

网址为:

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