【发布时间】: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”尝试应用程序时,它可以工作。但是在添加空格时失败并出现上述错误。