我有一个用于调出 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
}
}
这是字符串:
"https://itunes.apple.com/search?media=music&entity=song&term=The Chain"
最佳答案
您得到的是 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()
}
URL 将是:
https://itunes.apple.com/search?media=music&entity=song&term=The%20Chain
关于swift - URL 在 Swift 3 中始终为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46411038/