gpt4 book ai didi

swift - URL 在 Swift 3 中始终为 nil

转载 作者:搜寻专家 更新时间:2023-10-31 21:52:53 24 4
gpt4 key购买 nike

我有一个用于调出 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com