我有一个 URL 字符串,其末尾附加了变量,如下所示:
.../create?title=My Apartment
我想转义任何无效字符(如空格),但当我尝试这样做时,我使用以下命令在模拟器和我的设备 (iOS 8.0) 中崩溃:
NSLog("Item1: \(item)")
NSLog("Item2: \(item.title)")
if let scrubbed = item.title.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet()) {
NSLog("Scrubbed: \(scrubbed)")
} else {
NSLog("Nope!")
}
我在模拟器上看到的是这样的:
2014-09-24 16:59:19.120 MyApp[16406:171349] Item1: MyApp.PostItem
2014-09-24 16:59:19.121 MyApp[16406:171349] Item2: My Apartment
2014-09-24 16:59:19.125 MyApp[16406:171349] Scrubbed: My 0X0P+0partment
请注意该擦洗字符串的奇怪之处。不出所料,它在一段时间后崩溃,提示构造不当的 NSURL
对象。
当我在我的设备上运行这个程序时,我在试图打印的
NSLog()
语句上出现EXC_BAD_ACCESS
崩溃擦洗:
2014-09-24 17:04:37.378 MyApp[4346:2048259] Item1: MyApp.PostItem
2014-09-24 17:04:37.379 MyApp[4346:2048259] Item2: My Apartment
(lldb) po scrubbed
error: <EXPR>:1:1: error: non-nominal type '$__lldb_context' cannot be extended
extension $__lldb_context {
^
<EXPR>:11:5: error: 'PostManager.Type' does not have a member named '$__lldb_wrapped_expr_3'
$__lldb_injected_self.$__lldb_wrapped_expr_3(
^ ~~~~~~~~~~~~~~~~~~~~~~
(lldb)
我怎样才能弄清楚这里发生了什么?在它像这样崩溃之前,我本以为会在控制台中打印出 Nope!
。模型对象中的 String
值由 UITextField
提供。
编辑:我能够从 pre-scrubbed 值中获得一些 NSData
输出:
NSLog("Data: \(item.title.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false))")
...
2014-09-24 17:18:43.620 MyApp[4367:2051348] Data: Optional(<4d792041 70617274 6d656e74>)
编辑 2:我可以确认这个在 Xcode 中崩溃,并在 Playground 上通过。似乎是一个错误 - 但在哪里?代码?编译器?运行时?
编辑 3: 只有当我尝试使用 NSLog()
打印出变量值时,才会出现此错误。如果我完全避免这样做,而只是使用变量,那么每个人都会很高兴。
最佳答案
看起来像使用 NSCharacterSet.URLHostAllowedCharacterSet()
进行转义会生成奇怪的 unicode 字符串,如果使用此字符串作为第一个参数,它会强制 NSLog 崩溃。
有几种方法可以避免这种情况,您绝对应该使用它们:
就您在 URL 查询中使用它而言,您绝对应该使用不同的字符集 -
NSCharacterSet.URLQueryAllowedCharacterSet()
。使用
print/println
将
/li>scrubbed
作为参数传递给NSLog
NSLog("Scrubbed: %@", scrubbed)
任何这些“解决方法”都可以解决问题。
关于ios - Swift URL 字符串编码在 iOS 上崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26026570/