[英]Swift URL String encoding crashing on iOS?
我有一个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
对象,毫不奇怪。
当我在我的设备上运行此,我有崩溃EXC_BAD_ACCESS
上NSLog()
的是试图print语句Scrubbed:
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
提供。
编辑:我能够从预先擦除的值中获取一些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中确认此崩溃 ,并在操场上通过 。 似乎是一个错误 - 但在哪里? Xcode的? 编译器? 运行?
编辑3:如果我尝试使用NSLog()
打印出变量值,则只会出现此错误。 如果我完全避免这样做,只使用变量,每个人都很高兴。
看起来像使用NSCharacterSet.URLHostAllowedCharacterSet()
转义生成奇怪的unicode字符串,在使用此字符串作为第一个参数的情况下强制在NSLog中崩溃。
有几种方法可以避免这种情况,你肯定应该使用它们:
至于你在URL查询中使用它,你肯定应该使用不同的字符集 - NSCharacterSet.URLQueryAllowedCharacterSet()
。
使用print/println
通过scrubbed
到NSLog
作为参数NSLog("Scrubbed: %@", scrubbed)
任何这些“解决方法”都可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.