2017-09-25 39 views
0

我有一個用於調用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

回答

5

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