为什么我不能将此字符串转换为 URL? [英] Why can't I convert this String to a URL?

查看:38
本文介绍了为什么我不能将此字符串转换为 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 x 2 个关于 url 和 webViews 的问题.

I have x 2 questions about urls and webViews.

问题 1:我有一个从 API 获取的字符串,它应该是一个 url.字符串是 https://godochurch.blob.core.windows.net/sermons/1031/30-1-2017-Vision Sunday-Devotion.mp3

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

尝试转换为 url 时,我得到了 nil.

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

代码如下:

if let sermonUrl = sermonUrl {

        if let url = URL(string: sermonUrl) {

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

        }
    }

我发现Vision"和Sunday"之间的空格是问题所在.

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

在尝试将字符串转换为 URL 之前,我应该以某种方式对其进行编码吗?令人困惑的是,如果我将字符串粘贴到浏览器中,它就可以正常工作,但我注意到浏览器对空格进行了百分比编码.

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?

问题 2:我看到 URL(string: "urlStringHere") 仅适用于 iOS 10.我的应用程序需要适用于 iOS 9.如何转换上述代码使其适用于 iOS 9 和 10.

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.

提前感谢您的时间.

推荐答案

1: 用 %20+ 转义空间:

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 是在 Swift 3 中引入的,兼容 iOS 8 及更高版本.请参阅这个问题,了解如何使其适用于旧版本的 iOS.

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.

百分比转义 URL 的最简单方法是使用 URLComponents:

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 {
    // ... 
}

如果您碰巧从 Web 服务获取 URL 字符串并且其中包含空格,则该服务很糟糕.URL 中不允许有空格.Web 浏览器放宽了该规则,因为它们知道存在错误的 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.

这篇关于为什么我不能将此字符串转换为 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆