thecloud_of_unknowing
thecloud_of_unknowing

Reputation: 1205

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

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.

Upvotes: 0

Views: 613

Answers (1)

Code Different
Code Different

Reputation: 93161

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.

Upvotes: 3

Related Questions