URL is always nil in Swift 3

微笑、不失礼 提交于 2019-12-19 10:06:10

问题


I have a struct that I am using to call out to the iTunes API. But when ever I run it myURL variable is never getting set, it's always nil. Not sure what I am doing wrong:

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

Here's the string:

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

回答1:


You´re getting nil because the URL contains a space. You need to encode the string first and then convert it to an 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 will be:

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


来源:https://stackoverflow.com/questions/46411038/url-is-always-nil-in-swift-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!