Why can't I convert this String to a URL?

て烟熏妆下的殇ゞ 提交于 2020-02-08 05:14:50

问题


I have x 2 questions about urls and webViews.

Question 1: I have a string which I am getting from an API that is supposed to be a url. The string is https://godochurch.blob.core.windows.net/sermons/1031/30-1-2017-Vision Sunday-Devotion.mp3

When trying to convert to a url I'm getting nil.

Here is the code:

if let sermonUrl = sermonUrl {

        if let url = URL(string: sermonUrl) {

            let requestObj = URLRequest(url: url)
            webView.loadRequest(requestObj)

        }
    }

I have worked out that the space between 'Vision' and 'Sunday' is the problem.

Should I be encoding the string in some way before trying to convert it to a URL? What's confusing is that if I paste the string into my browser it works just fine, but I notice the browser is percent encoding the space.

If I am supposed to be encoding the string, how do I do that?

Question 2: I see that URL(string: "urlStringHere") is only available from iOS 10. My app needs to work for iOS 9. How can I convert the above code so it works on iOS 9 and 10.

Thanks in advance for your time.


回答1:


1: escape that space with %20 or +:

if let url = URL(string: "https://godochurch.blob.core.windows.net/sermons/1031/30-1-2017-Vision%20Sunday-Devotion.mp3") {
    // ...
}

2: URL was introduced with Swift 3, which is compatible with iOS 8 and later. See this question on how to make it work with older versions of iOS.


Edit: the easiest way to percent-escape a URL is to use URLComponents:

var components = URLComponents(string: "https://godochurch.blob.core.windows.net")!
components.path = "/sermons/1031/30-1-2017-Vision Sunday-Devotion.mp3"

if let url = components.url {
    // ... 
}

If you happen to get you URL strings from a webservice and it contains a space, that service is bad. Space is not allowed in an URL. Web browsers relax that rule because they know there are bad URLs out there. Swift won't take it.



来源:https://stackoverflow.com/questions/42029799/why-cant-i-convert-this-string-to-a-url

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