【问题标题】:Unable to encode String for URL in Swift 3无法在 Swift 3 中为 URL 编码字符串
【发布时间】:2017-06-07 00:38:54
【问题描述】:

我曾经使用 Objective-C 开发 iOS 应用程序。现在我最近迁移到了 Swift。在我的应用程序中,我有一个按钮可以打开带有预先填写的主题和正文的 MS Outlook 应用程序。

我在 Objective-C 中做了一个类似的应用程序,并使用下面的代码为 URL 编码我的字符串。

NSString *emailSubject = @"Test Subject";
NSString *encodedSubject = [emailSubject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];

现在我无法在 Swift 3 中做同样的事情。下面是我尝试过的代码。

var subjectText: String = "Test Subject"

var encodedSubject = subjectText.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

var stringURL: String = "ms-outlook://compose?subject=" + subjectText + "&body=TestingEmailNow"
// Convert the string to a URL.
var url = URL(string: stringURL)

// Open the app that responds to the URL scheme (should be Outlook).
UIApplication.shared.openURL(url!)

我得到的错误如下。

致命错误:在展开可选值时意外发现 nil 2017-06-07 04:29:35.158030+0400 我的应用程序 [1286:405793] 致命错误:在展开可选值时意外发现 nil

我知道这个错误是由于我的主题中的空间造成的。我可以这样说,因为如果我删除空间,我什至不必对其进行编码。它直接工作。我在这里做错了什么?

【问题讨论】:

  • 您发布的 Swift 代码不会因此错误而失败。你能告诉我们它实际失败的地方吗?
  • 我已经编辑了问题并发布了完整的按钮操作代码。当我使用“TestSubject”尝试应用程序时,它可以工作。但是在添加空格时失败并出现上述错误。

标签: ios swift3


【解决方案1】:

你犯了一个简单的错误。

检查你的线路

var stringURL: String = "ms-outlook://compose?subject=" + subjectText + "&body=TestingEmailNow"

您使用的是 subjectText 而不是 encodedSubject

完整代码:

var subjectText: String = "Test Subject"

var encodedSubject = subjectText.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

if let encodedSubject = encodedSubject {

    var stringURL: String = "ms-outlook://compose?subject=" + encodedSubject + "&body=TestingEmailNow"

    // Convert the string to a URL.
    var url = URL(string: stringURL)

    if let url = url {
        // Open the app that responds to the URL scheme (should be Outlook).
        UIApplication.shared.openURL(url)
    }
}

【讨论】:

  • 没问题!,既然您现在使用的是swift,我建议您使用“playgrounds”尝试这些简单的代码sn-ps。像这样的错误在那里很容易找到。
  • 我刚刚通过“解开”最终 URL 中的编码主题来编辑您的答案。
  • 你不需要解开编码的主题,这就是“如果让编码主题=编码主题”所做的。 if let 用于检查 nil 并同时将其解包以在 if 的范围内使用。您也可以使用具有相同效果的守卫。
  • 不解包,构建失败。
  • 你有没有:“如果让编码主题=编码主题{其余代码}”?
【解决方案2】:

使用的变量是问题,但我也建议使用 URLComponents 而不是将 URL 构建为字符串。

var subjectText: String = "Test Subject"

var components = URLComponents()

components.scheme = "ms-outlook"
components.host = "compose"

components.queryItems = [
    URLQueryItem(name: "subject", value: subjectText),
    URLQueryItem(name: "body", value: "TestingEmailNow")
]

if let url = components.url {
    UIApplication.shared.openURL(url)
}

【讨论】:

  • 我很想探索你的答案。现在肯定会试一试。
  • URLComponents 仅适用于 iOS 10+
  • 这真的很奇怪,我正在查看 swift playground 的应用内文档,上面写着 SDKs iOS 10.0+ macOS 10.12+ tvOS 10.0+ watchOS 3.0+ Unknown SDK 8.0+
  • 由于我的应用程序针对的是 iOS 10+,因此我接受了这个答案。 @Pochi 首先回答并解决了我的问题,所以我赞成。谢谢两位的支持。
猜你喜欢
  • 2017-02-28
  • 1970-01-01
  • 2017-08-25
  • 2017-08-05
  • 2019-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-04
相关资源
最近更新 更多